首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

HTML5 websocket实验,后台老板为golang http包使用

2013-03-12 
HTML5 websocket实验,后台为golang http包使用package mainimport (code.google.com/p/go.net/websocket

HTML5 websocket实验,后台为golang http包使用

package mainimport ("code.google.com/p/go.net/websocket""fmt""log""net/http""html/template")func Echo(ws *websocket.Conn){var err errorfor{fmt.Println("start")var reply stringif err = websocket.Message.Receive(ws, &reply); err != nil{fmt.Println("can't receive")break}fmt.Println("received back from client:"+ reply)msg := "Received : " + replyfmt.Println("Sending to cient: " + msg)if err =  websocket.Message.Send(ws, msg); err != nil{fmt.Println("Can't send")break}}}func chat(w  http.ResponseWriter, r *http.Request){r.ParseForm()fmt.Println(r.Form)t,_ := template.ParseFiles("websocket_demo.html")t.Execute(w, nil)}func main(){http.Handle("/", websocket.Handler(Echo))http.HandleFunc("/chat", chat)if err := http.ListenAndServe(":9999", nil); err != nil{log.Fatal("ListentAndServe:", err)}}==========================================================================================<html><head><body><script type="text/javascript">var sock = null;var wsuri = "ws://127.0.0.1:9999";window.onload = function(){console.log("onload");sock = new WebSocket(wsuri);sock.onopen = function(){console.log("connected to " + wsuri);}sock.onclose = function(e) {console.log("connection closed (" + e.code + ")");}sock.onmessage = function(e){console.log("message received:" + e.data);}};function send(){console.log("send")var msg = document.getElementById('message').value;console.log(msg)sock.send(msg);};</script><h1> Websocket Echo Test</h1><form><p>Message: <input id = "message" type = "text" value ="hello dumx"></p></form><button onclick="send();">Send Msg</button></body></head></html>


热点排行