Home  >  Article  >  Backend Development  >  How to send Go WebSocket messages?

How to send Go WebSocket messages?

WBOY
WBOYOriginal
2024-06-03 16:53:01999browse

In Go, you can use the gorilla/websocket package to send WebSocket messages. Specific steps: Establish a WebSocket connection. Send a text message: Call WriteMessage(websocket.TextMessage, []byte("message")). To send a binary message: call WriteMessage(websocket.BinaryMessage, []byte{1, 2, 3}).

Go WebSocket 消息如何发送?

#How to send Go WebSocket messages?

WebSocket is a high-level protocol for full-duplex communication over a single TCP connection. In Go, we can use the [gorilla/websocket](https://godoc.org/github.com/gorilla/websocket) package in the standard library to send WebSocket messages.

Send a text message

Here's how to send a text message:

func main() {
    ws, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080", nil)
    if err != nil {
        log.Fatal(err)
    }

    if err := ws.WriteMessage(websocket.TextMessage, []byte("Hello world!")); err != nil {
        log.Fatal(err)
    }
}

Send a binary message

To send a binary message, use websocket. BinaryMessage As the message type:

func main() {
    ws, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080", nil)
    if err != nil {
        log.Fatal(err)
    }

    if err := ws.WriteMessage(websocket.BinaryMessage, []byte{1, 2, 3}); err != nil {
        log.Fatal(err)
    }
}

Practical case: Chat room

In the chat room, the client sends messages through the WebSocket connection. Here is the client code:

func main() {
    ws, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080", nil)
    if err != nil {
        log.Fatal(err)
    }

    msg := "Hello from client!"
    if err := ws.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil {
        log.Fatal(err)
    }
}

This will send a WebSocket message to the server containing the text message Hello from client!.

The above is the detailed content of How to send Go WebSocket messages?. 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