-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
89 lines (81 loc) · 1.93 KB
/
server.go
File metadata and controls
89 lines (81 loc) · 1.93 KB
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 main
import (
"bufio"
"fmt"
"net"
)
type Message struct {
sender int
message string
}
func handleError(err error) {
// TODO: all
fmt.Println(err.Error())
panic(err)
}
func acceptConns(ln net.Listener, conns chan net.Conn) {
// TODO: all
for {
conn, err := ln.Accept()
if err != nil {
handleError(err)
}
conns <- conn
}
// Continuously accept a network connection from the Listener
// and add it to the channel for handling connections.
}
func handleClient(client net.Conn, clientid int, msgs chan Message) {
reader := bufio.NewReader(client)
for {
msg, err := reader.ReadString('\n')
if err != nil {
handleError(err)
}
fmt.Println(msg)
fmt.Println("Ok...")
message := Message{clientid, msg}
msgs <- message
}
// TODO: all
// So long as this connection is alive:
// Read in new messages as delimited by '\n's
// Tidy up each message and add it to the messages channel,
// recording which client it came from.
}
func main() {
//TODO Create a Listener for TCP connections on the port given above.
ln, err := net.Listen("tcp", ":8030")
if err != nil {
handleError(err)
}
//Create a channel for connections
conns := make(chan net.Conn)
//Create a channel for messages
msgs := make(chan Message)
//Create a mapping of IDs to connections
clients := make(map[int]net.Conn)
clientNumber := 0
//Start accepting connections
go acceptConns(ln, conns)
for {
select {
case conn := <-conns:
clients[clientNumber] = conn
go handleClient(conn, clientNumber, msgs)
clientNumber++
//TODO Deal with a new connection
// - assign a client ID
// - add the client to the clients channel
// - start to asynchronously handle messages from this client
case msg := <-msgs:
for i := 0; i < len(clients); i++ {
if i != msg.sender {
fmt.Fprint(clients[i], msg.message)
}
}
//TODO Deal with a new message
// Send the message to all clients that aren't the sender
}
}
}