/
main.go
81 lines (71 loc) · 1.63 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
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"strconv"
"github.com/Dongxiem/fastnet"
"github.com/Dongxiem/fastnet/connection"
"github.com/Dongxiem/fastnet/plugins/websocket/ws"
"github.com/Dongxiem/fastnet/plugins/websocket/ws/util"
)
type example struct{}
func (s *example) OnConnect(c *connection.Connection) {
log.Println(" OnConnect : ", c.PeerAddr())
}
func (s *example) OnMessage(c *connection.Connection, data []byte) (messageType ws.MessageType, out []byte) {
log.Println("OnMessage:", string(data))
messageType = ws.MessageBinary
switch rand.Int() % 3 {
case 0:
out = data
case 1:
msg, err := util.PackData(ws.MessageText, data)
if err != nil {
panic(err)
}
if err := c.Send(msg); err != nil {
msg, err := util.PackCloseData(err.Error())
if err != nil {
panic(err)
}
if e := c.Send(msg); e != nil {
panic(e)
}
}
case 2:
msg, err := util.PackCloseData("close")
if err != nil {
panic(err)
}
if e := c.Send(msg); e != nil {
panic(e)
}
}
return
}
func (s *example) OnClose(c *connection.Connection) {
log.Println("OnClose")
}
func main() {
handler := new(example)
var port int
var loops int
flag.IntVar(&port, "port", 1833, "server port")
flag.IntVar(&loops, "loops", -1, "num loops")
flag.Parse()
wsUpgrader := &ws.Upgrader{}
wsUpgrader.OnHeader = func(c *connection.Connection, key, value []byte) error {
fmt.Println(string(key), ":", string(value))
return nil
}
s, err := NewWebSocketServer(handler, wsUpgrader,
fastnet.Network("tcp"),
fastnet.Address(":"+strconv.Itoa(port)),
fastnet.NumLoops(loops))
if err != nil {
panic(err)
}
s.Start()
}