File: server.go

package info (click to toggle)
golang-github-francoispqt-gojay 1.2.13-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 1,456 kB
  • sloc: makefile: 86
file content (82 lines) | stat: -rw-r--r-- 1,490 bytes parent folder | download
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package server

import (
	"log"
	"math/rand"
	"net/http"
	"sync"
	"time"

	"github.com/francoispqt/gojay/examples/websocket/comm"
	"golang.org/x/net/websocket"
)

type server struct {
	clients []*Client
	mux     *sync.RWMutex
	handle  func(c *Client)
}

type Client struct {
	comm.SenderReceiver
	server *server
}

func NewClient(s *server, conn *websocket.Conn) *Client {
	sC := new(Client)
	sC.Conn = conn
	sC.server = s
	return sC
}

func NewServer() *server {
	s := new(server)
	s.mux = new(sync.RWMutex)
	s.clients = make([]*Client, 0, 100)
	return s
}

func (c *Client) Close() {
	c.Conn.Close()
}

func (s *server) Handle(conn *websocket.Conn) {
	defer func() {
		err := conn.Close()
		if err != nil {
			log.Fatal(err)
		}
	}()
	c := NewClient(s, conn)
	// add our server client to the list of clients
	s.mux.Lock()
	s.clients = append(s.clients, c)
	s.mux.Unlock()
	// init Client's sender and receiver
	c.Init(10)
	s.handle(c)
	// block until reader is done
	<-c.Dec.Done()
}

func (s *server) Listen(port string, done chan error) {
	http.Handle("/ws", websocket.Handler(s.Handle))
	done <- http.ListenAndServe(port, nil)
}

func (s *server) OnConnection(h func(c *Client)) {
	s.handle = h
}

func random(min, max int) int {
	rand.Seed(time.Now().Unix())
	return rand.Intn(max-min) + min
}

func (s *server) BroadCastRandom(sC *Client, m *comm.Message) {
	m.Message = "Random message"
	s.mux.RLock()
	r := random(0, len(s.clients))
	s.clients[r].SendMessage(m)
	s.mux.RUnlock()
}