forked from xaccc/webrtcServer
/
websoket.go
130 lines (104 loc) · 2.82 KB
/
websoket.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
package main
import (
"fmt"
"net/http"
"io"
"bufio"
"code.google.com/p/go.net/websocket"
"container/list"
)
var connid int
var conns *list.List
func ChatroomServer(ws *websocket.Conn){
defer ws.Close()
connid++
id := connid
fmt.Printf("connection id: %d\n",id)
item := conns.PushBack(ws)
defer conns.Remove(item)
name := fmt.Sprintf("user%d",id)
SendMessage(nil,fmt.Sprintf("{\"user_name\":\"%s\"}",name))
r := bufio.NewReader(ws)
for {
data,err := r.ReadBytes('\n')
if err != nil {
fmt.Printf("disconnected id : %d\n",id)
SendMessage(item, fmt.Sprintf("%s offline\n", name))
break
}
fmt.Printf("%s:%s",name,data)
SendMessage(item,fmt.Sprintf("%s\t>%s",name,data))
}
}
func SendMessage(self *list.Element,data string){
for item := conns.Front();item != nil ; item = item.Next() {
ws,ok := item.Value.(*websocket.Conn)
if !ok {
panic("item not *websocket.Conn")
}
if item == self {
continue
}
io.WriteString(ws,data)
}
}
func Client(w http.ResponseWriter, r *http.Request){
html := `<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>golang websocket chatroom</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var ws = new WebSocket("ws://127.0.0.1:6611/chatroom");
ws.onopen = function(e){
console.log("onopen");
console.dir(e);
};
ws.onmessage = function(e){
console.log("onmessage");
console.dir(e);
$('#log').append('<p>'+e.data+'<p>');
$('#log').get(0).scrollTop = $('#log').get(0).scrollHeight;
};
ws.onclose = function(e){
console.log("onclose");
console.dir(e);
};
ws.onerror = function(e){
console.log("onerror");
console.dir(e);
};
$(function(){
$('#msgform').submit(function(){
ws.send($('#msg').val()+"\n");
$('#log').append('<p style="color:red;">My > '+$('#msg').val()+'<p>');
$('#log').get(0).scrollTop = $('#log').get(0).scrollHeight;
$('#msg').val('');
return false;
});
});
</script>
</head>
<body>
<div id="log" style="height: 300px;overflow-y: scroll;border: 1px solid #CCC;">
</div>
<div>
<form id="msgform">
<input type="text" id="msg" size="60" />
</form>
</div>
</body>
</html>`
io.WriteString(w, html)
}
func main(){
connid = 0;
conns = list.New()
http.Handle("/chatroom", websocket.Handler(ChatroomServer));
http.HandleFunc("/", Client);
err := http.ListenAndServe(":6611", nil);
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}