forked from pschlump/socketio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
173 lines (155 loc) · 4.18 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package main
//
// Command line arguments can be used to set the IP address that is liseneed to and the port.
//
// $ ./chat --port=8080 --host=127.0.0.1
//
// Bring up a pair of browsers and chat betwen them.
//
import (
"fmt"
"github.com/SnowpMakes/socketio"
"log"
"net/http"
"os"
"sync"
"time"
flags "github.com/jessevdk/go-flags"
)
var port string = "9000"
var host_ip string = ""
var opts struct {
Port int `short:"P" long:"port" description:"Port to listen to" default:"9000"`
HostIP string `short:"H" long:"host" description:"Host or IP address to listen on" default:"localhost"`
}
// Simulate a user login -
// bob/123
// jane/abc
// are valid logins
func ValidateUser(un, pw string) (ok bool) {
ok = false
if un == "bob" && pw == "123" || un == "jane" && pw == "abc" {
ok = true
}
return
}
type UserInfo struct {
User string
IsLoggedIn bool
So socketio.Socket
}
var UserMap map[string]*UserInfo
var UserMapLock sync.RWMutex
func init() {
UserMap = make(map[string]*UserInfo)
}
func main() {
junk, err := flags.ParseArgs(&opts, os.Args)
if len(junk) != 1 {
fmt.Printf("Usage: Invalid arguments supplied, %s\n", junk)
os.Exit(1)
}
if err != nil {
os.Exit(1)
}
port = fmt.Sprintf("%d", opts.Port)
if opts.HostIP != "localhost" {
host_ip = opts.HostIP
}
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
server.On("connection", func(so socketio.Socket) {
log.Println("on connection")
so.Join("chat")
so.On("chat message", func(msg string) {
m := make(map[string]interface{})
m["a"] = "你好" // hello there
e := so.Emit("cn1111", m)
//这个没有问题 // this is no problem
fmt.Println("\n\n")
b := make(map[string]string)
b["u-a"] = "中文内容" //这个不能是中文 // this is chineese // this can not be chineese
m["b-c"] = b
e = so.Emit("cn2222", m)
log.Println(e)
log.Println("emit:", so.Emit("chat message", msg))
so.BroadcastTo("chat", "chat message", msg)
})
so.On("t45", func(msg string) {
err := so.Emit("r45", "Yep")
if err != nil {
fmt.Printf("Error: %s\n", err)
}
})
so.On("registerForName", func(name, pass string) {
b := ValidateUser(name, pass)
// store the soketio.Socket in a global map
UserMapLock.Lock()
UserMap[name] = &UserInfo{
User: name,
IsLoggedIn: b,
So: so,
}
UserMapLock.Unlock()
if b {
so.Emit("chat message", "logged in")
} else {
so.Emit("chat message", "invalid username/password (try bob/123 or jane/abc)")
}
})
so.On("logout", func(name string) {
UserMapLock.Lock()
delete(UserMap, name)
UserMapLock.Unlock()
so.Emit("chat message", "bye now")
})
so.On("sendMessageTo", func(iAm, name string, message string) {
fmt.Printf("sendMessage func, name = %v, message = %v", name, message)
UserMapLock.RLock()
defer UserMapLock.RUnlock()
from, ok1 := UserMap[iAm]
if !ok1 || !from.IsLoggedIn {
so.Emit("error", "Error: you are not logged in.")
return
}
dest, ok2 := UserMap[name]
if !ok2 || !dest.IsLoggedIn {
so.Emit("error", "Error: not logged in:"+name)
return
}
dest.So.Emit("chat message", message)
})
so.On("disconnection", func() {
// xyzzy - get "name" from so.Id() - use for auto/logout on disconnect - cleanup of global hash
log.Println("on disconnect")
})
})
server.On("error", func(so socketio.Socket, err error) {
log.Println("error:", err)
})
// ------------------ Send periodic time notices to client -------------------------------------------------------------------
ticker := time.NewTicker(10 * time.Second)
quit := make(chan struct{})
go func() {
for {
select {
case <-ticker.C:
// do stuff
server.BroadcastTo("chat", "chat message", "I am alive")
if u, ok := UserMap["bob"]; ok {
u.So.Emit("chat message", "Hi Bob!")
}
case <-quit:
ticker.Stop()
return
}
}
}()
http.Handle("/socket.io/", server)
http.Handle("/", http.FileServer(http.Dir("./asset")))
fmt.Printf("Serving on port %s, brows to http://localhost:%s/\n", port, port)
listen := fmt.Sprintf("%s:%s", host_ip, port)
log.Fatal(http.ListenAndServe(listen, nil))
}