-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathirc.go
61 lines (48 loc) · 1.14 KB
/
irc.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
package main
import (
"fmt"
"net/http"
"hash/fnv"
"golang.org/x/net/websocket"
)
var (
clients = make(map[ClientConn]int)
message = websocket.Message
)
type ClientConn struct {
websocket *websocket.Conn
ip string
}
func hash(s string) string {
h := fnv.New32a()
h.Write([]byte(s))
return fmt.Sprint(h.Sum32())[0:5]
}
func ircHandler(ws *websocket.Conn) {
var err error
var clientmessage string
current := ClientConn{ws, ws.Request().RemoteAddr}
clients[current] = 0
fmt.Println("number of clients connected ", len(clients))
for {
if err = message.Receive(ws, &clientmessage); err != nil {
delete(clients, current)
fmt.Println("client disconnect,", len(clients), " clients remain")
return
}
clientmessage = "<" + hash(current.ip) + "> " + clientmessage
for cs, _ := range clients {
if err = message.Send(cs.websocket, clientmessage); err != nil {
fmt.Println("sending failed")
}
}
}
}
func main() {
http.Handle("/irc", websocket.Handler(ircHandler))
http.Handle("/", http.FileServer(http.Dir(".")))
err := http.ListenAndServe(":1337", nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}