Skip to content

Commit

Permalink
新增NetConn接口
Browse files Browse the repository at this point in the history
  • Loading branch information
guonaihong committed Sep 5, 2023
1 parent aba7e1b commit 3101a33
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
5 changes: 5 additions & 0 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ func newConn(c net.Conn, client bool, conf *Config, fr fixedreader.FixedReader,
return con
}

// 返回标准库的net.Conn
func (c *Conn) NetConn() net.Conn {
return c.c
}

func (c *Conn) writeErrAndOnClose(code StatusCode, userErr error) error {
defer c.Callback.OnClose(c, userErr)
if err := c.WriteTimeout(opcode.Close, statusCodeToBytes(code), 2*time.Second); err != nil {
Expand Down
37 changes: 37 additions & 0 deletions conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,43 @@ func Test_WriteControl(t *testing.T) {
})
}

func Test_API(t *testing.T) {
t.Run("NetConn", func(t *testing.T) {
var shandler testPingPongCloseHandler
shandler.data = make(chan string, 1)
upgrade := NewUpgrade(WithServerBufioParseMode(), WithServerCallback(&shandler))
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, err := upgrade.Upgrade(w, r)
if err != nil {
t.Error(err)
}
if c.NetConn() != c.c {
t.Error("server.not equal")
}
c.StartReadLoop()
}))

defer ts.Close()

url := strings.ReplaceAll(ts.URL, "http", "ws")
con, err := Dial(url, WithClientOnMessageFunc(func(c *Conn, mt Opcode, payload []byte) {
}))
if err != nil {
t.Error(err)
}
defer con.Close()
if con.NetConn() != con.c {
t.Error("client.not equal")
}

err = con.WriteControl(Close, bytes.Repeat([]byte{1}, 126))
// 这里必须要报错
if err == nil {
t.Error("not error")
}
})
}

// 测试ping pong close control信息
func TestPingPongClose(t *testing.T) {
// 写一个超过maxControlFrameSize的消息
Expand Down

0 comments on commit 3101a33

Please sign in to comment.