Home  >  Article  >  Backend Development  >  How to implement WebSocket two-way communication in golang

How to implement WebSocket two-way communication in golang

WBOY
WBOYOriginal
2023-12-18 16:06:421282browse

How to implement WebSocket two-way communication in golang

How to implement two-way communication of WebSocket in Golang

WebSockets is a communication protocol that establishes a persistent connection between the client and the server, which allows two-way communication , and performs well in terms of real-time performance and efficiency. In Golang, we can use the net/http and gorilla/websocket packages in the standard library to implement WebSocket two-way communication. This article will introduce how to implement WebSocket two-way communication in Golang and provide specific code examples.

Step 1: Import dependency packages

First, we need to import the net/http and gorilla/websocket packages. The net/http package provides HTTP server and client functions, while the gorilla/websocket package is a WebSocket implementation library.

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

Step 2: Set the WebSocket processing function

Next, we need to set the WebSocket processing function. This function will handle the client's connection request and process the message sent by the client after the connection is successfully established.

func websocketHandler(w http.ResponseWriter, r *http.Request) {
    // 将 HTTP 连接升级为 WebSocket 连接
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println("Error upgrading HTTP connection to WebSocket:", err)
        return
    }

    // 在连接结束时关闭 WebSocket
    defer ws.Close()

    // 循环处理客户端发来的消息
    for {
        // 读取客户端发来的消息
        messageType, message, err := ws.ReadMessage()
        if err != nil {
            log.Println("Error reading message from WebSocket:", err)
            break
        }

        // 打印收到的消息
        log.Printf("Received message: %s", message)

        // 回复客户端收到的消息
        if err = ws.WriteMessage(messageType, message); err != nil {
            log.Println("Error writing message to WebSocket:", err)
            break
        }
    }
}

Step 3: Set up the WebSocket upgrader

In the processing function, we need to use the upgrader (upgrader) of the gorilla/websocket package to upgrade the HTTP connection to a WebSocket connection. The upgrader can also set some parameters such as allowed domains and handshake timeout.

var upgrader = websocket.Upgrader{
    // 允许跨域访问
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

Step 4: Set up the HTTP server

Finally, we need to set up the HTTP server and map the processing function to the corresponding path so that the client can connect to WebSocket through the path.

func main() {
    // 设置 WebSocket 处理函数
    http.HandleFunc("/", websocketHandler)

    // 启动 HTTP 服务器
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("Error starting HTTP server:", err)
    }
}

:8080 in the code example is the listening address and port number of the server. You can modify it as needed.

Using the above code, we have successfully implemented the function of two-way communication through WebSocket in Golang. After the client connection is successful, you can use code similar to the following to send and receive messages:

const socket = new WebSocket("ws://localhost:8080/");

socket.addEventListener("open", (event) => {
    socket.send("Hello, server!");
});

socket.addEventListener("message", (event) => {
    console.log("Received message from server:", event.data);
});

socket.addEventListener("close", (event) => {
    console.log("Server connection closed:", event);
});

In summary, we have introduced in detail how to implement WebSocket two-way communication in Golang and provided specific Code examples. Through these sample codes, you can quickly get started and implement real-time communication functions based on WebSocket.

The above is the detailed content of How to implement WebSocket two-way communication in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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