-
Notifications
You must be signed in to change notification settings - Fork 16
/
server.go
159 lines (131 loc) · 4.04 KB
/
server.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
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"net/http"
"os"
"github.com/kataras/neffos"
"github.com/kataras/neffos/gobwas"
"github.com/kataras/neffos/gorilla"
)
const (
endpoint = "localhost:8080"
namespace = "default"
timeout = 0 // 30 * time.Second
)
var handler = neffos.WithTimeout{
ReadTimeout: timeout,
WriteTimeout: timeout,
Namespaces: neffos.Namespaces{
namespace: neffos.Events{
neffos.OnNamespaceConnect: func(c *neffos.NSConn, msg neffos.Message) error {
return nil
},
neffos.OnNamespaceConnected: func(c *neffos.NSConn, msg neffos.Message) error {
log.Printf("[%s] connected to [%s].", c.Conn.ID(), msg.Namespace)
c.Emit("chat", []byte("welcome to server's namespace"))
return nil
},
neffos.OnNamespaceDisconnect: func(c *neffos.NSConn, msg neffos.Message) error {
log.Printf("[%s] disconnected from [%s].", c.Conn.ID(), msg.Namespace)
return nil
},
"chat": func(c *neffos.NSConn, msg neffos.Message) error {
log.Printf("--server-side-- send back the message [%s:%s]", msg.Event, string(msg.Body))
// c.Emit(msg.Event, msg.Body)
// c.Server().Broadcast(nil, msg) // to all including this connection.
c.Conn.Server().Broadcast(c.Conn, msg) // to all except this connection.
log.Printf("---------------------\n[%s] %s", c.Conn.ID(), msg.Body)
return nil
},
},
},
}
func main() {
args := os.Args[1:]
if len(args) > 1 {
log.Fatalf("expected program to start with 'gobwas' or 'gorilla' argument")
}
upgrader := gobwas.DefaultUpgrader
if len(args) > 0 {
method := args[0]
if method == "gorilla" {
upgrader = gorilla.DefaultUpgrader
log.Printf("Using with Gorilla Upgrader.")
}
}
server(upgrader)
}
var (
// tests immediately closed on the `Server#OnConnect`.
dissalowAll = false
// if not empty, tests broadcast on `Server#OnConnect` (expect this conn because it is not yet connected to any namespace locally).
notifyOthers = true
serverHandlesConnectNamespace = false
)
func server(upgrader neffos.Upgrader) {
srv := neffos.New(upgrader, handler)
// srv.IDGenerator = func(w http.ResponseWriter, r *http.Request) string {
// for k, v := range r.Header {
// log.Printf("%s=%s\n", k, v)
// }
// return neffos.DefaultIDGenerator(w, r)
// }
srv.OnConnect = func(c *neffos.Conn) error {
if c.WasReconnected() {
log.Printf("[%s] connection is a result of a client-side re-connection, with tries: %d", c.ID(), c.ReconnectTries)
}
if dissalowAll {
return fmt.Errorf("you are not allowed to connect here for some reason")
}
log.Printf("[%s] connected to server.", c.ID())
if serverHandlesConnectNamespace {
ns, err := c.Connect(nil, namespace)
if err != nil {
panic(err)
}
ns.Emit("chat", []byte("(Force-connected by server)"))
}
if notifyOthers {
c.Server().Broadcast(c, neffos.Message{
Namespace: namespace,
Event: "chat",
Body: []byte(fmt.Sprintf("Client [%s] connected too.", c.ID())),
})
}
return nil
}
srv.OnDisconnect = func(c *neffos.Conn) {
log.Printf("[%s] disconnected from the server.", c.ID())
}
srv.OnUpgradeError = func(err error) {
log.Printf("ERROR: %v", err)
}
mux := http.NewServeMux()
mux.Handle("/echo", srv)
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./browser/index.html")
}))
mux.Handle("/browserify/", http.StripPrefix("/browserify", http.FileServer(http.Dir("./browserify"))))
log.Printf("Listening on: %s\nPress CTRL/CMD+C to interrupt.", endpoint)
go http.ListenAndServe(endpoint, mux)
fmt.Fprint(os.Stdout, ">> ")
scanner := bufio.NewScanner(os.Stdin)
for {
if !scanner.Scan() {
log.Printf("ERROR: %v", scanner.Err())
return
}
text := scanner.Bytes()
if bytes.Equal(text, []byte("force disconnect")) {
srv.Do(func(c *neffos.Conn) {
c.DisconnectAll(nil)
}, false)
} else {
srv.Broadcast(nil, neffos.Message{Namespace: namespace, Event: "chat", Body: text})
}
fmt.Fprint(os.Stdout, ">> ")
}
} // Read more at: https://github.com/kataras/neffos