This repository has been archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
handleConnection.go
87 lines (73 loc) · 1.84 KB
/
handleConnection.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
package webwire
import (
"fmt"
"time"
)
func (srv *server) writeConfMessage(sock Socket) error {
writer, err := sock.GetWriter()
if err != nil {
return fmt.Errorf(
"couldn't get writer for configuration message: %s",
err,
)
}
if _, err := writer.Write(srv.configMsg); err != nil {
if closeErr := writer.Close(); closeErr != nil {
return fmt.Errorf(
"couldn't close writer after failed conf message write: %s: %s",
err,
closeErr,
)
}
return fmt.Errorf("couldn't write configuration message: %s", err)
}
if err := writer.Close(); err != nil {
return fmt.Errorf("couldn't close writer: %s", err)
}
return nil
}
func (srv *server) handleConnection(
connectionOptions ConnectionOptions,
sock Socket,
) {
// Send server configuration message
if err := srv.writeConfMessage(sock); err != nil {
srv.errorLog.Println("couldn't write config message: ", err)
if closeErr := sock.Close(); closeErr != nil {
srv.errorLog.Println("couldn't close socket: ", closeErr)
}
return
}
// Register connected client
connection := newConnection(
sock,
srv,
connectionOptions,
)
srv.connectionsLock.Lock()
srv.connections = append(srv.connections, connection)
srv.connectionsLock.Unlock()
// Call hook on successful connection
srv.impl.OnClientConnected(connectionOptions, connection)
for {
// Get a message buffer
msg := srv.messagePool.Get()
// Await message
if err := sock.Read(
msg,
time.Now().Add(srv.options.ReadTimeout), // Deadline
); err != nil {
msg.Close()
if !err.IsCloseErr() {
srv.warnLog.Printf("abnormal closure error: %s", err)
}
connection.Close()
srv.impl.OnClientDisconnected(connection, err)
break
}
// Parse & handle the message
if err := srv.handleMessage(connection, msg); err != nil {
srv.errorLog.Print("message handler failed: ", err)
}
}
}