这个程序简单,使用google go语言 golang和html5的websocket建立一个简单的web聊天程序。
程序如下:
1 package main
2
3 import (
4 "code.google.com/p/go.net/websocket"
5
6 "fmt"
7 "io"
8 "net/http"
9 )
10
11 func Echo(ws *websocket.Conn) {
12
13 var err error
14
15 mail := ws.Config().Location.Query().Get("mail")
16 mailto := ws.Config().Location.Query().Get("mailto")
17
18 fmt.Printf("%s, %s\n", mail, mailto)
19
20 mailmap[mail] = ws
21
22 fmt.Printf("%v\n", ws)
23
24 msgconnect := mail + " connect "
25 fmt.Println("server: " + msgconnect)
26
27 if err = websocket.Message.Send(ws, msgconnect); err != nil {
28 fmt.Println("Can't send")
29 return
30 }
31
32 for {
33 var reply string
34
35 if err = websocket.Message.Receive(ws, &reply); err != nil {
36 fmt.Println("Can't receive")
37 break
38 }
39
40 fmt.Println("Received back from client: " + reply)
41
42 wst, err1 := mailmap[mailto]
43 if !err1 {
44 msg := mailto + " not connect "
45 fmt.Println("server: " + msg)
46
47 if err = websocket.Message.Send(ws, msg); err != nil {
48 fmt.Println("Can't send")
49 break
50 }
51 continue
52 }
53
54 msg := mail + ":" + reply
55 fmt.Println("Sending to client: " + msg)
56
57 if err = websocket.Message.Send(wst, msg); err != nil {
58 fmt.Println("Can't send")
59 break
60 }
61 }
62 }
63
64 // 网页客户端
65 func Client(w http.ResponseWriter, r *http.Request) {
66 html := `<!doctype html>
67 <!doctype html>
68 <html>
69 <head>
70 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
71 <title>golang websocket chatroom</title>
72 <script src="http://img3.douban.com/js/packed_jquery.min6301986802.js"></script>
73
74 </head>
75 <body>
76 <h1>WebSocket chat with server </h1>
77 <div id="log" style="height: 300px;overflow-y: scroll;border: 1px solid #CCC;">
78 </div>
79 <div>
80
81 <p>
82 mail: <input id="mail" type="text" value="automate@qq.com">
83 </p>
84
85 <p>
86 mailto: <input id="mailto" type="text" value="program@qq.com"><button onclick="connectto();">Connect to</button>
87 </p>
88
89
90
91 <p>
92 Message: <input id="msg" type="text" value="Hello, world!"><button onclick="sendto();">Send Message</button>
93 </p>
94
95
96
97 </div>
98
99 </body>
100
101
102 <script>
103
104
105
106
107 function connectto() {
108 var mail = document.getElementById('mail').value;
109 console.log(mail);
110
111 var mailto = document.getElementById('mailto').value;
112 console.log(mailto);
113
114 var url = "ws://127.0.0.1:8001/chatroom?mailto=" + mailto + "&mail=" + mail;
115
116 ws = new WebSocket(url);
117
118 ws.onopen = function(e){
119 console.log("onopen");
120 console.dir(e);
121 };
122
123 ws.onmessage = function(e){
124 console.log("onmessage");
125 console.dir(e);
126 $('#log').append('<p>'+e.data+'<p>');
127 $('#log').get(0).scrollTop = $('#log').get(0).scrollHeight;
128 };
129
130 ws.onclose = function(e){
131 console.log("onclose");
132 console.dir(e);
133 };
134
135 ws.onerror = function(e){
136 console.log("onerror");
137 console.dir(e);
138 };
139
140
141 };
142
143 function sendto() {
144 var mail = document.getElementById('mail').value;
145 var msg = document.getElementById('msg').value;
146 $('#log').append('<p style="color:red;">' + mail + ' : '+msg+'<p>');
147 $('#log').get(0).scrollTop = $('#log').get(0).scrollHeight;
148
149 ws.send(msg);
150 };
151
152 </script>
153 </html>
154 `
155 io.WriteString(w, html)
156 }
157
158 var mailmap = make(map[string]*websocket.Conn, 10)
159
160 func main() {
161
162 fmt.Println("listen on port 8001")
163 fmt.Println("visit http://127.0.0.1:8001/chat with web browser(recommend: chrome)")
164
165 http.Handle("/", websocket.Handler(Echo))
166 http.HandleFunc("/chat", Client)
167 err := http.ListenAndServe(":8001", nil)
168
169 if err != nil {
170 panic("ListenAndServe: " + err.Error())
171 }
172 }
173
运行
http://127.0.0.1:8001/chat在两个不同的浏览器下 互给用户名,连接后就可以开始聊天
如下图:
posted on 2012-12-20 15:32
漂漂 阅读(4356)
评论(1) 编辑 收藏 引用