-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws_session.go
51 lines (44 loc) · 929 Bytes
/
ws_session.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
package dnet
import (
"bytes"
"fmt"
"io"
"net"
"reflect"
)
type DefWsCodec struct{}
//解码
func (_ DefWsCodec) Decode(reader io.Reader) (interface{}, error) {
buff := new(bytes.Buffer)
_, err := buff.ReadFrom(reader)
if err != nil {
return nil, err
}
return buff.Bytes(), nil
}
//编码
func (_ DefWsCodec) Encode(o interface{}) ([]byte, error) {
data, ok := o.([]byte)
if !ok {
return nil, fmt.Errorf("dnet:defWSCodec encode interface{} is %s, need type []byte", reflect.TypeOf(o))
}
return data, nil
}
type WSSession struct {
*session
}
// NewWSSession return an initialized *WSSession
func NewWSSession(conn net.Conn, options ...Option) *WSSession {
op := loadOptions(options...)
if op.MsgCallback == nil {
// need message callback
panic(ErrNilMsgCallBack)
}
// init default codec
if op.Codec == nil {
op.Codec = DefWsCodec{}
}
return &WSSession{
session: newSession(conn, op),
}
}