deprecated_overflow_gateway.../server.go
crusader 5be418700f ing
2017-08-24 19:43:32 +09:00

74 lines
1.7 KiB
Go

package overflow_gateway_websocket
import (
"log"
"git.loafle.net/overflow/overflow_gateway_websocket/clients"
"git.loafle.net/overflow/overflow_gateway_websocket/websocket"
"github.com/valyala/fasthttp"
)
type ()
type Server interface {
ListenAndServe(addr string) error
}
type server struct {
_option *Options
_clientPption *clients.Options
_upgrader *websocket.Upgrader
_clients map[string]clients.Client
}
func NewServer(o *Options) Server {
s := &server{
_option: o.Validate(),
_clients: make(map[string]clients.Client, 100),
}
s._upgrader = &websocket.Upgrader{
ReadBufferSize: s._option.ReadBufferSize,
WriteBufferSize: s._option.WriteBufferSize,
HandshakeTimeout: s._option.HandshakeTimeout,
}
s._clientPption = &clients.Options{
OnRequest: s._option.OnRequest,
OnDisconnected: s.onDisconnected,
ReadTimeout: s._option.ReadTimeout,
WriteTimeout: s._option.WriteTimeout,
ReadBufferSize: s._option.ReadBufferSize,
WriteBufferSize: s._option.WriteBufferSize,
MaxMessageSize: s._option.MaxMessageSize,
}
return s
}
func (s *server) onPush(cb OnPushFunc) {
}
func (s *server) onDisconnected(c clients.Client) {
delete(s._clients, c.ID())
s._option.OnDisconnected(c)
}
func (s *server) onConnection(ctx *fasthttp.RequestCtx) {
s._upgrader.Upgrade(ctx, nil, func(conn *websocket.Conn, err error) {
if err != nil {
log.Print("upgrade:", err)
return
}
cid := s._option.IDGenerator(ctx)
c := clients.New(cid, s._clientPption, ctx, conn)
s._clients[cid] = c
s._option.OnConnection(c)
})
}
func (s *server) ListenAndServe(addr string) error {
return fasthttp.ListenAndServe(addr, s.onConnection)
}