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.
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.
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 }
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.).
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 }
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) } }
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 } // 将消息保存到数据库... } }
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!