ing
This commit is contained in:
parent
3fdde4c8f2
commit
8a0c8265ee
33
server.go
33
server.go
@ -2,7 +2,6 @@ package overflow_gateway_websocket
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"git.loafle.net/overflow/overflow_gateway_websocket/websocket"
|
||||
"github.com/valyala/fasthttp"
|
||||
@ -10,16 +9,9 @@ import (
|
||||
|
||||
type ()
|
||||
|
||||
type sendRequest struct {
|
||||
s Socket
|
||||
m []byte
|
||||
}
|
||||
|
||||
type Server interface {
|
||||
ListenAndServe(addr string) error
|
||||
HandleSocket(pattern string, o *SocketOptions)
|
||||
Send(soc Socket, m []byte)
|
||||
SendAll(m []byte)
|
||||
}
|
||||
|
||||
type server struct {
|
||||
@ -27,11 +19,8 @@ type server struct {
|
||||
_upgrader *websocket.Upgrader
|
||||
_handlers map[string]*SocketOptions
|
||||
_sockets map[string]Socket
|
||||
_sIdMtx sync.Mutex
|
||||
_addSocketCh chan Socket
|
||||
_removeSocketCh chan Socket
|
||||
_sendCh chan sendRequest
|
||||
_sendAllCh chan []byte
|
||||
}
|
||||
|
||||
func NewServer(o *ServerOptions) Server {
|
||||
@ -41,8 +30,6 @@ func NewServer(o *ServerOptions) Server {
|
||||
_sockets: make(map[string]Socket, 100),
|
||||
_addSocketCh: make(chan Socket),
|
||||
_removeSocketCh: make(chan Socket),
|
||||
_sendCh: make(chan sendRequest),
|
||||
_sendAllCh: make(chan []byte),
|
||||
}
|
||||
|
||||
s._upgrader = &websocket.Upgrader{
|
||||
@ -90,9 +77,7 @@ func (s *server) onConnection(ctx *fasthttp.RequestCtx) {
|
||||
s.onError(ctx, fasthttp.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
s._sIdMtx.Lock()
|
||||
id := s._option.IDGenerator(ctx)
|
||||
s._sIdMtx.Unlock()
|
||||
soc := NewSocket(id, path, co, conn)
|
||||
s.addSocket(soc)
|
||||
s._option.OnConnection(soc)
|
||||
@ -111,26 +96,12 @@ func (s *server) listenHandler() {
|
||||
// remove a socket
|
||||
case soc := <-s._removeSocketCh:
|
||||
delete(s._sockets, soc.ID())
|
||||
case sr := <-s._sendCh:
|
||||
sr.s.Write(sr.m)
|
||||
case m := <-s._sendAllCh:
|
||||
for _, soc := range s._sockets {
|
||||
soc.Write(m)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) Send(soc Socket, m []byte) {
|
||||
r := sendRequest{
|
||||
s: soc,
|
||||
m: m,
|
||||
}
|
||||
s._sendCh <- r
|
||||
}
|
||||
|
||||
func (s *server) SendAll(m []byte) {
|
||||
s._sendAllCh <- m
|
||||
func (s *server) Sockets() map[string]Socket {
|
||||
return s._sockets
|
||||
}
|
||||
|
||||
func (s *server) HandleSocket(pattern string, o *SocketOptions) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user