Skip to content

Commit

Permalink
Fix #78 && add unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
Allenxuxu committed Apr 9, 2021
1 parent 7ac1dc1 commit 2e912ef
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
1 change: 0 additions & 1 deletion connection/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ func (c *Connection) Close() error {

// ShutdownWrite 关闭可写端,等待读取完接收缓冲区所有数据
func (c *Connection) ShutdownWrite() error {
c.connected.Set(false)
return unix.Shutdown(c.fd, unix.SHUT_WR)
}

Expand Down
54 changes: 53 additions & 1 deletion example/websocket/wsserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,17 @@ import (
"github.com/Allenxuxu/gev/plugins/websocket/ws"
"github.com/Allenxuxu/gev/plugins/websocket/ws/util"
"github.com/Allenxuxu/toolkit/sync"
"github.com/Allenxuxu/toolkit/sync/atomic"
"github.com/stretchr/testify/assert"
"golang.org/x/net/websocket"
)

type wsExample struct{}
type wsExample struct {
ClientNum atomic.Int64
}

func (s *wsExample) OnConnect(c *connection.Connection) {
s.ClientNum.Add(1)
//log.Println(" OnConnect : ", c.PeerAddr())
}
func (s *wsExample) OnMessage(c *connection.Connection, data []byte) (messageType ws.MessageType, out []byte) {
Expand Down Expand Up @@ -53,6 +58,7 @@ func (s *wsExample) OnMessage(c *connection.Connection, data []byte) (messageTyp
}

func (s *wsExample) OnClose(c *connection.Connection) {
s.ClientNum.Add(-1)
//log.Println("OnClose")
}

Expand Down Expand Up @@ -117,3 +123,49 @@ func startWebSocketClient(addr string) {
}
}
}

func TestWebSocketServer_CloseConnection(t *testing.T) {
rand.Seed(time.Now().UnixNano())
handler := new(wsExample)

s, err := NewWebSocketServer(handler, &ws.Upgrader{},
gev.Address(":1833"),
gev.NumLoops(8),
gev.ReusePort(true))
if err != nil {
t.Fatal(err)
}

go func() {
time.Sleep(time.Second)

var (
err error
n = 100
toClose = 50
conn = make([]*websocket.Conn, n)
addr = "ws://localhost" + s.Options().Address
)

for i := 0; i < n; i++ {
conn[i], err = websocket.Dial(addr, "", addr)
if err != nil {
panic(err)
}

}
assert.Equal(t, n, int(handler.ClientNum.Get()))

for i := 0; i < toClose; i++ {
if err := conn[i].Close(); err != nil {
panic(err)
}
}
time.Sleep(time.Second)
assert.Equal(t, n-toClose, int(handler.ClientNum.Get()))

s.Stop()
}()

s.Start()
}

0 comments on commit 2e912ef

Please sign in to comment.