-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_socket.go
81 lines (70 loc) · 1.46 KB
/
tcp_socket.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
package main
import (
"encoding/json"
"log"
"net"
"time"
)
//type tcpConn net.Conn // invalid receiver type *tcpConn (tcpConn is an interface type)
type tcpConn struct {
net.Conn
}
// {"MessageType":1,"RoomId":1,"Content":"enter"}
func (c *tcpConn) ReadChatMessage(msg *Message) error {
var bufferSize = 1024
data := make([]byte, bufferSize)
n, err := c.Read(data)
if err != nil {
log.Println("tcp read error: ", err)
return err
}
log.Println("read data from tcp socket:", data[:n], "EOF")
json.Unmarshal(data[:n], msg)
log.Println("read message from tcp socket:", msg)
msg.CreatedAt = time.Now()
return nil
}
func (c *tcpConn) WriteChatMessage(msg *Message) error {
b, err := json.Marshal(msg)
if err != nil {
log.Println("message marshal error: ", err)
}
_, err = c.Write(b)
if err != nil {
log.Println("tcp write error: ", err)
return err
}
return nil
}
func (c *tcpConn) Close() error {
err := c.Close()
if err != nil {
log.Println("tcp close error: ", err)
return err
}
return nil
}
func (c *tcpConn) RemoteAddr() string {
return c.RemoteAddr()
}
func (c *tcpConn) Quit() <-chan struct{} {
return nil
}
func handleTcp(c net.Conn) {
tcpConn := &tcpConn{Conn: c}
newClient(tcpConn, "", "")
}
func runTcp(addr string) {
log.Println("start tcp server")
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(err)
}
for {
c, err := l.Accept()
if err != nil {
log.Println("tcp accept error: ", err)
}
handleTcp(c)
}
}