How to use Go and http.Transport for WebSocket communication?
WebSocket is a protocol that provides two-way communication in network applications. It allows the server to actively push messages to the client without requiring the client to initiate a request first. In Go language, you can use http.Transport to create and manage WebSocket connections.
The following is a sample code for WebSocket communication using Go and http.Transport:
package main import ( "fmt" "log" "net/http" "golang.org/x/net/websocket" ) func EchoServer(ws *websocket.Conn) { for { var message string err := websocket.Message.Receive(ws, &message) if err != nil { log.Println("receive failed:", err) break } log.Println("received:", message) err = websocket.Message.Send(ws, message) if err != nil { log.Println("send failed:", err) break } log.Println("sent:", message) } } func main() { http.Handle("/", websocket.Handler(EchoServer)) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
The above code creates a WebSocket server that sends the received message back to the client intact. In the main function, we use http.Handle and websocket.Handler to register the EchoServer function as a processor. Then use http.ListenAndServe to start the server listening on port 8080.
On the client side, we can use http.Transport to create a WebSocket connection and send and receive data through the Send and Receive methods. The following is a simple client sample code:
package main import ( "fmt" "log" "net/http" "golang.org/x/net/websocket" ) func main() { origin := "http://localhost/" url := "ws://localhost:8080/" ws, err := websocket.Dial(url, "", origin) if err != nil { log.Fatal("dial failed:", err) } message := "Hello, WebSocket!" err = websocket.Message.Send(ws, message) if err != nil { log.Fatal("send failed:", err) } var response string err = websocket.Message.Receive(ws, &response) if err != nil { log.Fatal("receive failed:", err) } fmt.Println("received:", response) }
In the above code, we use websocket.Dial to create a WebSocket connection. Then use the websocket.Message.Send method to send the message, and use websocket.Message.Receive to receive the message returned by the server.
With the above code example, we can easily create and manage WebSocket connections using Go and http.Transport. WebSocket provides efficient and real-time two-way communication capabilities for applications and is suitable for many different application scenarios. Hope this article is helpful to you!
The above is the detailed content of How to use Go and http.Transport for WebSocket communication?. For more information, please follow other related articles on the PHP Chinese website!