aboutsummaryrefslogtreecommitdiff
path: root/internal/net/server_test.go
blob: fca55282535b480de59ae31a14634e850775184d (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
package net

import (
	"sync"
	"testing"
)

func TestHubConcurrency(t *testing.T) {
	h := NewHub()
	h.OnRemove(func(s *Session) {})

	var wg sync.WaitGroup
	const n = 50

	for i := 0; i < n; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			s := &Session{}
			h.Add(s)
			h.EnterRoom(s, 1)
			h.PlayersInRoom(1)
			h.LeaveRoom(s)
			h.HardRemove(s)
		}()
	}

	for i := 0; i < n; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			h.AllSessions()
		}()
	}

	wg.Wait()
}

type testConn struct{ data []byte }

func (c *testConn) ReadMessage() (string, error)   { return "", nil }
func (c *testConn) Write(b []byte) (int, error)      { c.data = append(c.data, b...); return len(b), nil }
func (c *testConn) Close() error                      { return nil }
func (c *testConn) SetEcho(bool) error                { return nil }

func TestSessionWriteConcurrency(t *testing.T) {
	conn := &testConn{}
	sess := &Session{Conn: conn}

	var wg sync.WaitGroup
	const n = 50

	for i := 0; i < n; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			sess.Write("hello")
			sess.WriteLine("world")
			sess.Writef("formatted %d", 42)
		}()
	}

	wg.Wait()
}