-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_server.go
103 lines (87 loc) · 2.16 KB
/
tcp_server.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"bufio"
"log"
"net"
)
// Client holds info about connection
type Client struct {
conn net.Conn
Server *server
}
// TCP server
type server struct {
address string // Address to open connection: localhost:9999
onNewClientCallback func(c *Client)
onClientConnectionClosed func(c *Client, err error)
onNewMessage func(c *Client, message string)
}
// Read client data from channel
func (c *Client) listen() {
reader := bufio.NewReader(c.conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
c.conn.Close()
c.Server.onClientConnectionClosed(c, err)
return
}
c.Server.onNewMessage(c, message)
}
}
// Send text message to client
func (c *Client) Send(message string) error {
_, err := c.conn.Write([]byte(message))
return err
}
// Send bytes to client
func (c *Client) SendBytes(b []byte) error {
_, err := c.conn.Write(b)
return err
}
func (c *Client) Conn() net.Conn {
return c.conn
}
func (c *Client) Close() error {
return c.conn.Close()
}
// Called right after server starts listening new client
func (s *server) OnNewClient(callback func(c *Client)) {
s.onNewClientCallback = callback
}
// Called right after connection closed
func (s *server) OnClientConnectionClosed(callback func(c *Client, err error)) {
s.onClientConnectionClosed = callback
}
// Called when Client receives new message
func (s *server) OnNewMessage(callback func(c *Client, message string)) {
s.onNewMessage = callback
}
// Start network server
func (s *server) Listen() {
listener, err := net.Listen("tcp", s.address)
if err != nil {
log.Fatal("Error starting TCP server.")
}
defer listener.Close()
for {
conn, _ := listener.Accept()
client := &Client{
conn: conn,
Server: s,
}
go client.listen()
s.onNewClientCallback(client)
}
}
// Creates new tcp server instance
func NewTCPServer(address string) *server {
log.Println("Creating TCP server with address", address)
server := &server{
address: address,
}
server.OnNewClient(func(c *Client) {})
server.OnNewMessage(func(c *Client, message string) {})
server.OnClientConnectionClosed(func(c *Client, err error) {})
return server
}