How to receive Go WebSocket messages?

WBOY
Release: 2024-06-02 14:47:57
Original
598 people have browsed it

The method of receiving WebSocket messages in Go depends on the client and server side: Client: Use the ReadMessage function to read the message and return the message type, payload and error. Server: Read the ReadMessage method of the connected client, which also returns the message type, payload and error.

Go WebSocket 消息如何接收?

How to receive Go WebSocket messages?

WebSocket is a full-duplex communication protocol that allows clients and servers to communicate in both directions after establishing a single connection. This article explains how to receive WebSocket messages in Go.

Client receives messages

On the client, you can receive messages through the ReadMessage function:

import "github.com/gorilla/websocket"

type Message struct {
    Type int
    Payload []byte
}

func readMessage(conn *websocket.Conn) (*Message, error) {
    mt, r, err := conn.ReadMessage()
    if err != nil {
        return nil, err
    }

    return &Message{
        Type:    mt,
        Payload: r,
    }, nil
}
Copy after login

ReadMessage The function returns three Values: message type (mt), message payload (r), and an error (err). The message type is an integer value indicating the type of message (text, binary, etc.).

Server receives messages

On the server side, you can receive messages through the ReadMessage method of client connection:

func (c *Client) readMessage() (*Message, error) {
    mt, r, err := c.conn.ReadMessage()
    if err != nil {
        return nil, err
    }

    return &Message{
        Type:    mt,
        Payload: r,
    }, nil
}
Copy after login

Practical case

The following is an example of a Go client that receives WebSocket messages and outputs them to the console:

package main

import (
    "fmt"
    "log"

    "github.com/gorilla/websocket"
)

func main() {
    conn, _, err := websocket.DefaultDialer.Dial("ws://example.com/ws", nil)
    if err != nil {
        log.Fatal("dial:", err)
    }
    defer conn.Close()

    for {
        _, message, err := conn.ReadMessage()
        if err != nil {
            if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway,
                websocket.CloseAbnormalClosure) {
                log.Fatal("unexpected close:", err)
            }
            continue
        }

        fmt.Printf("received: %s\n", message)
    }
}
Copy after login

Similarly, the following is an example of a Go server that receives WebSocket messages and stores them in the database:

package main

import (
    "database/sql"
    "fmt"
    "log"

    "github.com/gorilla/websocket"
)

func main() {
    // 数据库设置...

    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Fatal("upgrade:", err)
    }
    defer conn.Close()

    for {
        _, message, err := conn.ReadMessage()
        if err != nil {
            if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway,
                websocket.CloseAbnormalClosure) {
                log.Fatal("unexpected close:", err)
            }
            continue
        }

        // 将消息保存到数据库...
    }
}
Copy after login

The above is the detailed content of How to receive Go WebSocket messages?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
go
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!