-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatServer.go
89 lines (74 loc) · 2.17 KB
/
chatServer.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
package nan0chat
import (
"github.com/Yomiji/nan0"
"time"
"fmt"
"github.com/golang/protobuf/proto"
)
type ChatServer struct {
users map[int64]*ConnectedUser
internal *nan0.Service
}
type ConnectedUser struct {
conn nan0.NanoServiceWrapper
}
func Serve(port int) (err error) {
// create the server descriptor
service := &ChatServer{
internal: &nan0.Service{
ServiceName: "Nan0 Chat",
Port: int32(port),
HostName: "localhost",
StartTime: time.Now().Unix(),
ServiceType: "Chat",
},
users: make(map[int64]*ConnectedUser),
}
// build server and start listening for clients
server, err := service.internal.NewNanoBuilder().
AddMessageIdentity(proto.Clone(new(ChatMessage))).
EnableEncryption(KeysToNan0Bytes(*EncryptKey, *Signature)).
ToggleWriteDeadline(true).
BuildServer(nil)
if err != nil {
return err
}
// shutdown server on exit or error
defer server.Shutdown()
fmt.Println("Secure nan0chat server started. Use interrupt command (ctrl+c) to exit.")
// start handling client requests indefinitely
for ; ; {
func() {
defer func() { recover() }()
// when we get a new connection, create a random user id, save the connection to the map of connected clients
conn := <-server.GetConnections()
newUserId := random.Int63()
service.users[newUserId] = &ConnectedUser{
conn: conn,
}
fmt.Printf("New user %v connected.\n", newUserId)
// start a service handler for all messages generated by that client
go service.startDistributor(newUserId, conn)
}()
}
return
}
// Starts a handler for the given user that will distribute the user's messages to each other connected user
func (s *ChatServer) startDistributor(userId int64, conn nan0.NanoServiceWrapper) {
defer conn.Close()
receiver := conn.GetReceiver()
for ; ; {
msg := <-receiver
// if we have some data inside the message
if msg != nil {
// broadcast the message to all connected clients that are NOT the client that generated the message
// we assume that the subject client has kept track of its own message
for id, user := range s.users {
if id != userId {
sender := user.conn.GetSender()
sender <- msg
}
}
}
}
}