Skip to content

Commit

Permalink
新增NetConn接口 (#14)
Browse files Browse the repository at this point in the history
* 新增NetConn接口

* 更新
  • Loading branch information
guonaihong committed Sep 5, 2023
1 parent aba7e1b commit 3842c68
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions common_options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1555,6 +1555,7 @@ func Test_CommonOption(t *testing.T) {
t.Errorf("write message or read message fail:got:%s, need:hello\n", d)
}
case <-time.After(1000 * time.Millisecond):
t.Errorf("write message timeout\n")
}
if atomic.LoadInt32(&run) != 1 {
t.Error("not run server:method fail")
Expand Down
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 3842c68

Please sign in to comment.