前端之家收集整理的这篇文章主要介绍了
Golang websocket使用方法,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main
import (
"fmt"
"log"
"net/http"
"code.google.com/p/go.net/websocket"
)
func main() {
http.Handle("/",websocket.Handler(Echo))
if err := http.ListenAndServe(":1234",nil); err != nil {
log.Fatal("ListenAndServer: ",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)
if err = websocket.Message.Send(ws,msg); err != nil {
fmt.Println("Can't send")
break
}
}
}