To create WebSocket communication with Golang, you only need to use the golang.org/x/net/websocket package, which may be walled and cannot be downloaded using go get, but we can provide it from Goang China. address Download and put the package in the corresponding path.
WebSocket is a communication protocol, aiming at improving the efficiency of HTTP as a stateless protocol. WebSocket is a full duplex connection between client and server. Client and server can use this connection to communicate only once. In our project, the general client is the front-end page, using JavaScript to create a WebSocket to communicate with the back-end WebSocket server.
Let's first look at our server-side code
package main import ( "fmt" "html/template" "net/http" "os" "strings" "golang.org/x/net/websocket" ) func upper(ws *websocket.Conn) { var err error for { var reply string if err = websocket.Message.Receive(ws, &reply); err != nil { fmt.Println(err) continue } if err = websocket.Message.Send(ws, strings.ToUpper(reply)); err != nil { fmt.Println(err) continue } } } func index(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { return } t, _ := template.ParseFiles("index.html") t.Execute(w, nil) } func main() { http.Handle("/upper", websocket.Handler(upper)) http.HandleFunc("/", index) if err := http.ListenAndServe(":9999", nil); err != nil { fmt.Println(err) os.Exit(1) } }
From the main function, we create a Server using Golang's http package. The Server can handle two requests, one is /, which is the root path of the Web project. The index function is used as the processing method to return index.html to the home page.
Server also processes/upper requests, which are processed by a WebSocket function. It wraps up the upper function defined by ourselves. The upper function has one parameter, that is, the server creates a good WebSocket connection. The upper function logic is very simple. It reads the request content of the server through the WebSocket connection, converts the content into capitals, and then uses WebSocket to convert the result. Return to the client.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Websocket</title> </head> <body> <h1>String conversion uppercase</h1> <form> <p> //String: <input id= "content" type= "text" placeholder= "input string to be converted"> </p> </form> <label id="result">The result is:</label><br><br> <button onclick="send()">Transformation</button> <script type="text/javascript"> var sock = null; var wsuri = "ws://127.0.0.1:9999/upper"; sock = new WebSocket(wsuri); sock.onmessage = function(e) { var result = document.getElementById('result'); result.innerHTML = "The result is:" + e.data; } function send() { var msg = document.getElementById('content').value; sock.send(msg); } </script> </body> </html>
On the front-end page, we mainly look at the JavaScript code section. First, we build a global WebSocket, and then when we click the conversion button, we send the input content through WebSocket. WebSocket's onmessage function is used to deal with the response of the server. There are also onerror, onclose and other methods, which are error callback and closing callback of WebSocket. This paper does not use the onmessage function, which is generally used to deal with resource recovery and error reporting.
Golang can easily use WebSocket, just wrap a handler with websocket.Handler.