修复websocket
This commit is contained in:
@ -3,6 +3,7 @@ package ws
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
|
"log"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Packet struct {
|
type Packet struct {
|
||||||
@ -27,16 +28,21 @@ func Binary(buf []byte) *Packet {
|
|||||||
type Conn struct {
|
type Conn struct {
|
||||||
WriteChan chan *Packet
|
WriteChan chan *Packet
|
||||||
ReadChan chan []byte
|
ReadChan chan []byte
|
||||||
ctx context.Context
|
Context context.Context
|
||||||
|
cancel context.CancelFunc
|
||||||
conn *websocket.Conn
|
conn *websocket.Conn
|
||||||
close bool
|
close bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func Wrap(conn *websocket.Conn) *Conn {
|
func Wrap(conn *websocket.Conn) *Conn {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
return &Conn{
|
return &Conn{
|
||||||
WriteChan: make(chan *Packet),
|
WriteChan: make(chan *Packet),
|
||||||
ReadChan: make(chan []byte),
|
ReadChan: make(chan []byte),
|
||||||
conn: conn,
|
conn: conn,
|
||||||
|
Context: ctx,
|
||||||
|
cancel: cancel,
|
||||||
|
close: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,6 +50,9 @@ func (conn *Conn) ReadLoop() {
|
|||||||
for !conn.close {
|
for !conn.close {
|
||||||
_, message, err := conn.conn.ReadMessage()
|
_, message, err := conn.conn.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if !websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseAbnormalClosure) {
|
||||||
|
log.Println("websocket read error:", err)
|
||||||
|
}
|
||||||
conn.Close()
|
conn.Close()
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@ -63,16 +72,14 @@ func (conn *Conn) WriteLoop() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
default:
|
case <-conn.Context.Done():
|
||||||
if conn.close {
|
return
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (conn *Conn) Close() error {
|
func (conn *Conn) Close() error {
|
||||||
conn.ReadChan <- nil
|
conn.cancel()
|
||||||
conn.close = true
|
conn.close = true
|
||||||
return conn.conn.Close()
|
return conn.conn.Close()
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user