Home > Backend Development > Golang > Golang implements websocket

Golang implements websocket

王林
Release: 2023-05-22 14:45:08
Original
2436 people have browsed it

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.

What is WebSocket

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:

  1. The client initiates a WebSocket connection request.
  2. After receiving the request, the server performs a handshake protocol and confirms that the WebSocket connection can be used.
  3. After the WebSocket connection is established, the client and server can conduct real-time two-way communication.
  4. If the server needs to send data to the client, it can send it directly to the client and vice versa.

Compared with traditional HTTP requests, the advantages of WebSocket are:

  1. Real-time two-way communication, suitable for online games, real-time chat, online video and other real-time applications Application scenarios.
  2. Fewer requests and responses, reducing network bandwidth consumption and improving data transmission efficiency.

Go implements WebSocket

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.

Establishing a WebSocket connection

To establish a WebSocket connection, we need to perform the following operations on the server and client respectively:

Server

  1. Create an HTTP service, use the 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")
})
Copy after login
  1. Perform the connection establishment operation in the WebSocket communication processing function.
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
        }
    }
}
Copy after login

Client

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);
};
Copy after login

Send message

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");
Copy after login

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)
Copy after login

Send a message from the server:

err = conn.WriteMessage(websocket.TextMessage, []byte("Hello world"))
if err != nil {
    log.Println("Write error:", err)
    return
}
Copy after login

On the client Receive and process messages:

socket.onmessage = function(event) {
    console.log("Received: " + event.data);
};
Copy after login

WebSocket error handling

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()
Copy after login

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
}
Copy after login

In the client, we can handle WebSocket errors through the onerror event, for example:

socket.onerror = function(event) {
    console.log("WebSocket error: " + event.data);
};
Copy after login

Summary

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template