首先获取websocket包, 在获取的时候好像需要下载什么什么hg的一个软件之后可以成功执行
go get code.google.com/p/go.net/websocket
步入正题
服务端:
import (
"code.google.com/p/go.net/websocket"
"fmt"
"log"
"net/http"
)
func main() {
fmt.Println("Start app")
http.Handle("/", websocket.Handler(Echo))
if err := http.ListenAndServe(":4001", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
func Echo(ws *websocket.Conn) {
var err error
for {
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 client: " + msg + "_server")
if err = websocket.Message.Send(ws, msg+"_server"); err != nil {
fmt.Println("Can't send")
break
}
}
}
客户端:
<html>
<head></head>
<body>
<script type="text/javascript">
var sock = null;
var wsuri = "ws://127.0.0.1:4001";
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() {
var msg = document.getElementById('message').value;
sock.send(msg);
}
</script>
<h1>WebSocket Echo Test</h1>
<form>
<p>Message: <input id="message" type="text" value="Hello, world!"></p>
</form>
<button onclick="send();">Send Message</button>
</body>
</html>
启动服务器, 成功显示Start app
当客户端将用户输入的信息Send之后,服务器端通过Receive接收到了相应信息,然后通过Send发送了应答信息。
页面信息:
客户端发送信息之后服务端输出:
客户端发送信息之后客户端输出:
希望对大家能有所帮助!