Home >Backend Development >Golang >How does the Go WebSocket client connect?
Go WebSocket Client Connection Guide The following steps demonstrate how to use Go's gorilla/websocket package to establish a connection with a WebSocket server: Import the necessary libraries: Import the github.com/gorilla/websocket package and other necessary packages. Dial-up connection: Use the DefaultDialer.Dial function to connect to the server, providing the server URL. Sending a message: Use the WriteMessage function to send a message to the server. Read the message: Use the ReadMessage function to read the response message from the server.
WebSocket is a full-duplex communication protocol built on TCP, allowing two-way communication between the client and the server. When using WebSockets in Go, you need to connect to a server in order to communicate.
The following example demonstrates how to use Go's github.com/gorilla/websocket
package to establish a WebSocket client connection:
package main import ( "fmt" "log" "github.com/gorilla/websocket" ) func main() { url := "ws://localhost:8080/ws" conn, _, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("dial:", err) } defer conn.Close() if err := conn.WriteMessage(websocket.BinaryMessage, []byte("Hello WebSocket!")); err != nil { log.Println("write:", err) } msgType, msg, err := conn.ReadMessage() if err != nil { log.Println("read:", err) } fmt.Printf("Received: %s\n", string(msg)) }
Suppose you have the following scenario:
localhost:8080
. Then you can use the following code to establish a client connection:
conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080/ws", nil) if err != nil { log.Fatal("dial:", err) }
If the connection is successful, you can send a message to the WebSocket server like the following:
if err := conn.WriteMessage(websocket.BinaryMessage, []byte("Hello WebSocket!")); err != nil { log.Println("write:", err) }
Then , you can read the response message from the server:
msgType, msg, err := conn.ReadMessage() if err != nil { log.Println("read:", err) }
In the above example, websocket.BinaryMessage
is used to send a binary message. You can use different message types according to your needs.
The above is the detailed content of How does the Go WebSocket client connect?. For more information, please follow other related articles on the PHP Chinese website!