Home  >  Article  >  Backend Development  >  How to use WebSocket for cross-platform communication in golang

How to use WebSocket for cross-platform communication in golang

WBOY
WBOYOriginal
2023-12-18 12:09:19686browse

How to use WebSocket for cross-platform communication in golang

WebSocket is a technology used for real-time two-way communication between a web browser and a server. It provides a reliable way to send and receive data and is more efficient and faster than the traditional HTTP request-response mechanism. In golang, we can use third-party libraries to support WebSocket communication. This article will introduce how to use the gorilla/websocket library to implement WebSocket communication and provide specific code examples.

  1. Install gorilla/websocket library

You can easily install the gorilla/websocket library using the go get command:

go get github.com/gorilla/websocket
  1. Create WebSocket connection

On the server side, use the Upgrader function of the gorilla/websocket library to upgrade the HTTP connection to a WebSocket connection. The code is as follows:

import (
    "net/http"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func myHandler(w http.ResponseWriter, r *http.Request) {
    // 将HTTP连接升级为WebSocket连接
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        // 处理错误
        return
    }

    // 处理WebSocket连接
    for {
        // 读取消息
        messageType, p, err := conn.ReadMessage()
        if err != nil {
            // 处理错误
            return
        }

        // 处理消息
        err = conn.WriteMessage(messageType, p)
        if err != nil {
            // 处理错误
            return
        }
    }
}

func main() {
    http.HandleFunc("/", myHandler)
    http.ListenAndServe(":8080", nil)
}

On the client side, we can use JavaScript code to create a WebSocket connection. The code is as follows:

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

ws.onopen = function() {
    console.log("WebSocket连接已打开");
};

ws.onmessage = function(evt) {
    console.log("接收到消息: " + evt.data);
};

ws.onclose = function() {
    console.log("WebSocket连接已关闭");
};
  1. Sending and receiving messages

On the server side, we can use the WriteMessage function to send messages to the client. The code is as follows:

err := conn.WriteMessage(websocket.TextMessage, []byte("Hello, client!"))
if err != nil {
    // 处理错误
    return
}

On the client, we can use the send function to send messages and the onmessage function to receive messages. The code is as follows:

ws.send("Hello, server!");

ws.onmessage = function(evt) {
    console.log("接收到消息: " + evt.data);
};
  1. Processing WebSocket requests

In actual applications, we may need to perform authentication and authorization when processing WebSocket requests. In this case, we can use HTTP headers to pass authentication information. For example, you can add information similar to the following in the HTTP header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Then, on the server side, we can use the CheckOrigin option of the Upgrader function to check the origin of the WebSocket request and use the authentication in the HTTP header information to process the request. The specific code is as follows:

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    CheckOrigin: func(r *http.Request) bool {
        // 检查请求的来源
        if r.Header.Get("Origin") != "http://localhost:8080" {
            return false
        }

        // 检查认证信息
        if r.Header.Get("Authorization") != "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" {
            return false
        }

        return true
    },
}

func myHandler(w http.ResponseWriter, r *http.Request) {
    // 将HTTP连接升级为WebSocket连接
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        // 处理错误
        return
    }

    // 处理WebSocket连接
    for {
        // 读取消息
        messageType, p, err := conn.ReadMessage()
        if err != nil {
            // 处理错误
            return
        }

        // 处理消息
        err = conn.WriteMessage(messageType, p)
        if err != nil {
            // 处理错误
            return
        }
    }
}
  1. Summary

This article introduces how to use the gorilla/websocket library to implement WebSocket communication in golang, and provides specific code examples. With WebSocket technology, we can build efficient, real-time two-way communication applications, such as online chat rooms and multiplayer games. In practical applications, we also need to consider issues such as security and reliability, such as authentication and authorization, handling exceptions, etc.

The above is the detailed content of How to use WebSocket for cross-platform 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