-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
130 lines (105 loc) · 2.56 KB
/
main.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/* Gavin Langdon
* Network Programming
* Spring 2013
* Chat server
*/
package main
import (
"net"
"container/list"
"flag"
)
var VerboseMode = flag.Bool("v", false, "Verbose mode--enables logging of messages")
var ListenPort string
func init() {
flag.Parse()
if flag.NArg() < 1 {
panic("Port not specified")
}
ListenPort = ":" + flag.Arg(0)
}
// Custom list so we have a Find method
type List struct {
*list.List
}
func (l *List) Find(value interface{}) *list.Element {
for e := l.Front(); e != nil; e = e.Next() {
if e.Value == value {
return e
}
}
return nil
}
// Listen to the TCP connection
func listen(listener net.Listener, mainChan chan net.Conn) {
for {
conn, err := listener.Accept()
if err != nil {
err.Error()
return
}
// Send new connection to the dispatcher loop
mainChan <- conn
}
}
type UDPListener struct {
connSet map[string] *FauxConn
mainConn net.PacketConn
closeCh chan string
}
func (l *UDPListener) flushCloses() {
for {
select {
// Since the deletion does not occur until after the ReadFrom returns,
// the user is technically not deleted until the next udp message is received.
// This means that if the same user were to reconnect in the next udp message,
// he would be deleted without a response. However udp doesn't guarantee messages
// be received at all, so the user can just be forced to retype the message.
case closedIP := <-l.closeCh:
delete(l.connSet, closedIP)
default:
return
}
}
}
// Listen to the TCP connection
func listenUDP(mainChan chan net.Conn) error {
conn, err := net.ListenPacket("udp", ListenPort)
if err != nil {
return err
}
l := UDPListener{make(map[string] *FauxConn), conn, make(chan string, 10)}
for {
l.flushCloses()
buf := make([]byte, 1024)
count, addr, err := conn.ReadFrom(buf)
if err != nil {
return err
}
fc := l.connSet[addr.String()]
if fc == nil {
fc = NewFauxConn(addr, l.mainConn, l.closeCh)
l.connSet[addr.String()] = fc
// Inform the dispatcher of the new connection
mainChan <- fc
}
// Send buffer to the client's buffer channel
fc.inCh <- buf[:count]
}
return nil
}
func main() {
var err error
mainChan := make(chan net.Conn, 10)
// Start dispatch loop
go Dispatch(mainChan)
listener, err := net.Listen("tcp", ListenPort)
defer listener.Close()
if err != nil {
return
}
// start udp loop
go listenUDP(mainChan)
// Start TCP loop
listen(listener, mainChan)
}