HTML部分
在网页上放置一个按钮和一个文本框,按钮用来向服务器发送信息,文本框用来显示从服务器传回的消息。
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> <script type="text/javascript" src="js/loli.js"></script> </head> <body> <p><input id="btn1" type="button" value="按钮" /></p> <p><input id="txt1" type="text" /></p> </body> </html>
WebSocket部分
window.onload = main; var ws; function main() { var oBtn = document.getElementById('btn1'); oBtn.onclick = OnButton1; } function OnButton1() { ws = new WebSocket('ws://localhost/ws'); ws.onopen = OnOpen; ws.onmessage = OnMessage; } function OnOpen(event) { ws.send('hello websocket'); } function OnMessage(event) { var oTxt = document.getElementById('txt1'); oTxt.value = event.data; };
后端部分
要想处理WebSocket请求,必须有一个
func (*websocket.Conn)类型的处理函数,例如:
func OnWebSocket(ws *websocket.Conn) { defer ws.Close() var err error var str string for { if err = websocket.Message.Receive(ws, &str); err != nil { break } else { fmt.Println("从客户端收到:", str) } str = "hello, I'm server." if err = websocket.Message.Send(ws, str); err != nil { break } else { fmt.Println("向客户端发送:", str) } } }
然后和一个网址对应起来:
http.Handle("/ws", websocket.Handler(OnWebSocket))
完整代码如下:
package main import ( "bytes" "errors" "fmt" "html/template" "net/http" "runtime" "golang.org/x/net/websocket" ) // 端口 const ( HTTP_PORT string = "80" HTTPS_PORT string = "443" ) // 目录 const ( CSS_CLIENT_PATH = "/css/" DART_CLIENT_PATH = "/js/" IMAGE_CLIENT_PATH = "/image/" CSS_SVR_PATH = "web" DART_SVR_PATH = "web" IMAGE_SVR_PATH = "web" ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) } func main() { // 先把css和脚本服务上去 http.Handle(CSS_CLIENT_PATH, http.FileServer(http.Dir(CSS_SVR_PATH))) http.Handle(DART_CLIENT_PATH, http.FileServer(http.Dir(DART_SVR_PATH))) // 网址与处理逻辑对应起来 http.HandleFunc("/", HomePage) http.Handle("/ws", websocket.Handler(OnWebSocket)) // 开始服务 err := http.ListenAndServe(":"+HTTP_PORT, nil) if err != nil { fmt.Println("服务失败 /// ", err) } } func WriteTemplateToHttpResponse(res http.ResponseWriter, t *template.Template) error { if t == nil || res == nil { return errors.New("WriteTemplateToHttpResponse: t must not be nil.") } var buf bytes.Buffer err := t.Execute(&buf, nil) if err != nil { return err } res.Header().Set("Content-Type", "text/html; charset=utf-8") _, err = res.Write(buf.Bytes()) return err } func HomePage(res http.ResponseWriter, req *http.Request) { t, err := template.ParseFiles("web/loli.html") if err != nil { fmt.Println(err) return } err = WriteTemplateToHttpResponse(res, t) if err != nil { fmt.Println(err) return } } func OnWebSocket(ws *websocket.Conn) { defer ws.Close() var err error var str string for { if err = websocket.Message.Receive(ws, &str); err != nil { break } else { fmt.Println("从客户端收到:", str) } str = "hello, I'm server." if err = websocket.Message.Send(ws, str); err != nil { break } else { fmt.Println("向客户端发送:", str) } } }