With the continuous development of Internet technology, real-time connection has become an essential function for more and more applications. WebSocket is a network protocol based on the TCP protocol that allows the server to push data to the client to achieve real-time two-way communication.
Go is a fast and efficient programming language. Due to its simplicity and efficiency, it has become one of the most popular languages in recent years. In this article, we will introduce how to implement WebSocket service using Go language.
The WebSocket protocol is a full-duplex communication protocol based on the TCP protocol that allows real-time communication between the client and the server. Compared with the traditional HTTP request and response mode, WebSocket can maintain the connection state after the connection is established, thereby achieving real-time two-way communication.
The workflow of the WebSocket protocol is as follows:
Compared with traditional HTTP requests, the advantages of WebSocket are:
Go is an emerging language. Due to its simplicity, efficiency, security and other characteristics, more and more teams are beginning to use Go to develop network applications. In Go, there is a standard library net/http that provides APIs to implement HTTP and WebSocket services.
To establish a WebSocket connection, we need to perform the following operations on the server and client respectively:
http.HandleFunc
function to register a router, and allow the corresponding routing processing function to perform WebSocket communication. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // 判断是否支持 WebSocket,如果支持则进入 WebSocket 通信处理函数。 if websocket.IsWebSocketUpgrade(r) { websocket.Handler(handleWebSocket).ServeHTTP(w, r) return } http.ServeFile(w, r, "index.html") })
func handleWebSocket(conn *websocket.Conn) { defer conn.Close() // 输出日志信息,表示已经建立连接。 log.Println("WebSocket connected") for { // 读取客户端发送过来的消息。 _, msg, err := conn.ReadMessage() if err != nil { log.Println("Read error:", err) return } // 输出日志信息,表示接收到客户端发送的消息。 log.Printf("Received: %s ", msg) // 处理完毕后,发送消息。 err = conn.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Println("Write error:", err) return } } }
In the client, we need to use JavaScript code to operate the WebSocket connection. The specific code is as follows:
var socket = new WebSocket("ws://127.0.0.1:8080/"); socket.onopen = function() { console.log("WebSocket connected"); }; socket.onmessage = function(event) { console.log("Received: " + event.data); }; socket.onclose = function(event) { console.log("WebSocket closed"); }; socket.onerror = function(event) { console.log("WebSocket error: " + event.data); };
When the WebSocket connection is established, the server and the client can conduct real-time two-way communication. The server can send messages to the client through the conn.WriteMessage
function, and the client can send messages to the server through the socket.send
function.
Send a message from the client:
socket.send("Hello world");
Receive and process the message on the server:
_, msg, err := conn.ReadMessage() if err != nil { log.Println("Read error:", err) return } log.Printf("Received: %s ", msg)
Send a message from the server:
err = conn.WriteMessage(websocket.TextMessage, []byte("Hello world")) if err != nil { log.Println("Write error:", err) return }
On the client Receive and process messages:
socket.onmessage = function(event) { console.log("Received: " + event.data); };
In actual development, WebSocket may encounter various abnormal situations, such as network interruption, connection timeout, server crash, etc. In Go, we can handle these exceptions through error handling.
In the server, we can use the defer
statement to release resources, such as closing the WebSocket connection, etc.
defer conn.Close()
At the same time, during the process of websocket communication processing function, we need to preprocess errors that may occur. For example:
_, msg, err := conn.ReadMessage() if err != nil { log.Println("Read error:", err) return }
In the client, we can handle WebSocket errors through the onerror
event, for example:
socket.onerror = function(event) { console.log("WebSocket error: " + event.data); };
This article introduces How to use Go language to implement WebSocket service, including establishing WebSocket connection, sending messages, exception handling, etc. The WebSocket protocol provides a real-time two-way communication method and can be used in real-time application scenarios such as online games, real-time chat, and online video. In Go, the WebSocket service can be easily implemented using the API provided by the standard library net/http.
The above is the detailed content of Golang implements websocket. For more information, please follow other related articles on the PHP Chinese website!