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

rufidmx · · 1591 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

package main
import (
"code.google.com/p/go.net/websocket"
"fmt"
"log"
"net/http"
"html/template"
)

func Echo(ws *websocket.Conn){
var err error
for{
fmt.Println("start")
var reply string
if err = websocket.Message.Receive(ws, &reply); err != nil{
fmt.Println("can't receive")
break
}

fmt.Println("received back from client:"+ reply)
msg := "Received : " + reply
fmt.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>



有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:rufidmx

查看原文:HTML5 websocket实验,后台为golang http包使用

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1591 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传