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}).
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.
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) } }
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) } }
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!