golang(5):编写WebSocket服务,客户端和html5调用
本文的原文连接是: http://www.52php.cn/article/p-qveauntj-ber.html 转载请必须注明出处! 1,关于websocketHTML5定义了WebSocket协议,能更好的节省服务器资源和带宽并达到实时通讯。 2,安装websocket使用的golang官方的net包下面的websocket,地址: 首先设置go_path变量,参考: 下载net包,安装websocket模块 #全部模块下载
go get github.com/golang/net
#做下软连接把github文件夹下面的映射到golang.org下,否则其他模块如html安装不上。
ln -s /usr/local/go_path/src/github.com/golang/net /usr/local/go_path/src/golang.org/x/net
#安装websocket模块
go install golang.org/x/net/websocket
这个模块的包结构都统一成golang.org/x/net。使用import “golang.org/x/net/websocket”引入。 文档在:(godoc是非常不错的网站,所有golang的文档都在上面。) 3,代码和运行代码: package main
import (
"golang.org/x/net/websocket"
"fmt"
"log"
"net/http"
)
func echoHandler(ws *websocket.Conn) {
msg := make([]byte,512)
n,err := ws.Read(msg)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Receive: %sn",msg[:n])
send_msg := "[" + string(msg[:n]) + "]"
m,err := ws.Write([]byte(send_msg))
if err != nil {
log.Fatal(err)
}
fmt.Printf("Send: %sn",msg[:m])
}
func main() {
http.Handle("/echo",websocket.Handler(echoHandler))
http.Handle("/",http.FileServer(http.Dir(".")))
err := http.ListenAndServe(":8080",nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
客户端websocket调用代码: package main
import (
"golang.org/x/net/websocket"
"fmt"
"log"
)
var origin = "http://127.0.0.1:8080/"
var url = "ws://127.0.0.1:8080/echo"
func main() {
ws,err := websocket.Dial(url,"",origin)
if err != nil {
log.Fatal(err)
}
message := []byte("hello,world!你好")
_,err = ws.Write(message)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Send: %sn",message)
var msg = make([]byte, 512)
m,err := ws.Read(msg)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Receive: %sn",msg[:m])
ws.Close()//关闭连接
}
客户端使用websocket.Dial(url,“”,origin) 进行websocket连接,但是origin参数并没有实际调用。 4,html5调用使用jquery了。用百度的cdn: <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Sample of websocket with golang</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script> $(function() { var ws = new WebSocket("ws://localhost:8080/echo"); ws.onmessage = function(e) { $('<li>').text(event.data).appendTo($ul); }; var $ul = $('#msg-list'); $('#sendBtn').click(function(){ var data = $('#name').val(); ws.send(data); }); }); </script>
</head>
<body>
<input id="name" type="text"/>
<input type="button" id="sendBtn" value="send"/>
<ul id="msg-list"></ul>
</body>
</html>
当点击button按钮之后,websocket收到onmessage事件,然后把数据显示到页面。 5,总结本文的原文连接是: http://www.52php.cn/article/p-qveauntj-ber.html 转载请必须注明出处! 使用golang开发websocket非常简单。 非常方便,因为nodejs做服务器的时候会出现服务器负载突然高的情况,而且nodejs的库非常杂和多,解决起来可能比较麻烦。 我还是比较倾向于用golang开发。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |