-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
74 lines (54 loc) · 1.64 KB
/
websocket.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
/*Package websocket provides rich websocket support for the ion web framework.
Source code and other details for the project are available at GitHub:
https://github.com/get-ion/websocket
Installation
$ go get -u github.com/get-ion/websocket
Example code:
package main
import (
"fmt"
"github.com/get-ion/ion"
"github.com/get-ion/ion/context"
"github.com/get-ion/websocket"
)
func main() {
app := ion.New()
app.Get("/", func(ctx context.Context) {
ctx.ServeFile("websockets.html", false)
})
setupWebsocket(app)
// x2
// http://localhost:8080
// http://localhost:8080
// write something, press submit, see the result.
app.Run(ion.Addr(":8080"))
}
func setupWebsocket(app *ion.Application) {
// create our echo websocket server
ws := websocket.New(websocket.Config{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
})
ws.OnConnection(handleConnection)
// register the server's endpoint.
// see the inline javascript code in the websockets.html,
// this endpoint is used to connect to the server.
app.Get("/echo", ws.Handler())
// serve the javascript built'n client-side library,
// see weboskcets.html script tags, this path is used.
app.Any("/ion-ws.js", func(ctx context.Context) {
ctx.Write(websocket.ClientSource)
})
}
func handleConnection(c websocket.Connection) {
// Read events from browser
c.On("chat", func(msg string) {
// Print the message to the console
fmt.Printf("%s sent: %s\n", c.Context().RemoteAddr(), msg)
// Write message back to the client message owner:
// c.Emit("chat", msg)
c.To(websocket.Broadcast).Emit("chat", msg)
})
}
*/
package websocket