Download WebSocket Package
If the download fails, it may be a wall.
Package golang.org/x/net/websocket:unrecognized Import Path "Golang.org/x/net/websocket" (https Fetch:get https:// Golang.org/x/net/websocket?go-get=1:dial TCP 216.239.37.1:443:CONNECTEX:A connection attempt failed because the Connec Ted Party didn't properly respond after a period of time, or established connection failed because connected host had FAI led to respond.)
Can try
$ go get -u github.com/golang/net/websocket
Remember to change the path to Golang.org/x/net/websocket after downloading
$ cd $GOPATH$ mkdir -p golang.org/x/net$ cp github.com/golang/net/websocket/ golang.org/x/net/ -R
Instance Service-side code
Server.go
Package Mainimport ("FMT" "Golang.org/x/net/websocket" "html/template"//Support Template HTML "log" "Net/http") func Echo (ws *websocket. Conn) {var err error for {var reply string//websocket Accept information If Err = WebSocket. Message.receive (WS, &reply); Err! = Nil {fmt. Println ("Receive failed:", err) break} fmt. Println ("Reveived from client:" + Reply) Msg: = "Received:" + Reply FMT. Println ("Send to Client:" + msg)//Here is the send message if Err = WebSocket. Message.send (WS, MSG); Err! = Nil {fmt. Println ("Send failed:", err) Break}}}func Web (w http. Responsewriter, R *http. Request) {//Print the requested method FMT. Println ("Method", R.method) if R.method = = "Get" {//If the request method is a get display login.html, and corresponding to the front end T, _: = template. Parsefiles ("websocket.html") T.execute (W, Nil)} else {//otherwise go Print output post accept parameters username and password Fmt. Println (R.postformvalue ("username")) fmt. Println (R.postformvalue ("Password")}}func Main () {//Accept the route address HTTP for WebSocket. Handle ("/websocket", WebSocket. Handler (Echo))//html page http. Handlefunc ("/web", web) If err: = http. Listenandserve (": 1234", nil); Err! = Nil {log. Fatal ("Listenandserve:", Err)}}
Client code
Websocket.html
<! DOCTYPE html>
TestStart the service side
$ ./server
Launch browser
Input Http://127.0.0.1:1234/web
Network communication content, first load the page, and then use HTTP to establish a websocket connection, the subsequent communication directly using WebSocket.
Click on the SendMessage button in the page
Server-Side output:
Method GET
Reveived from Client:hello, world!
Send to Client:received:Hello, world!
Browser output:
ReferenceHttps://github.com/astaxie/build-web-application-with-golang/blob/master/zh/08.2.md
Https://github.com/ukai/go-websocket-sample/blob/master/websocket_echo_sample.go
Golang How to use WebSocket