Home >Backend Development >Golang >How to use WebSocket for remote control in golang
How to use WebSocket for remote control in Go language
Introduction:
WebSocket is a way to achieve real-time two-way communication in Web applications technology. In the Go language, we can use the net/http
and github.com/gorilla/websocket
packages in the standard library to implement WebSocket communication. This article will introduce how to use WebSocket for remote control in Go language and provide specific code examples.
Steps:
go get github.com/gorilla/websocket
package main import ( "log" "net/http" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{} func wsHandler(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Fatal(err) } defer conn.Close() for { // 读取客户端消息 messageType, p, err := conn.ReadMessage() if err != nil { log.Println(err) return } // 处理客户端消息 // doSomething(p) // 响应客户端消息 err = conn.WriteMessage(messageType, p) if err != nil { log.Println(err) return } } } func main() { http.HandleFunc("/ws", wsHandler) log.Fatal(http.ListenAndServe(":8080", nil)) }
package main import ( "log" "net/url" "os" "os/signal" "time" "github.com/gorilla/websocket" ) func main() { interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/ws"} log.Printf("connecting to %s", u.String()) c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatal("dial:", err) } defer c.Close() done := make(chan struct{}) // 启动读取协程 go func() { defer c.Close() defer close(done) for { _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) return } // 处理服务器消息 // doSomething(message) } }() // 启动写入协程 go func() { defer c.Close() defer close(done) for { // 写入消息到服务器 err := c.WriteMessage(websocket.TextMessage, []byte("Hello, Server!")) if err != nil { log.Println("write:", err) return } time.Sleep(time.Second) } }() // 等待中断信号,优雅地关闭连接 for { select { case <-done: return case <-interrupt: log.Println("interrupt") return } } }
$ go build server.go $ go build client.go $ ./server $ ./client
Summary:
Through the above steps, we can use WebSocket in Go language remote control. On the server side, we use the github.com/gorilla/websocket
package to create and manage WebSocket connections through conn.ReadMessage()
and conn.WriteMessage()
Methods to read and send messages. On the client side, we can connect to WebSocket through websocket.DefaultDialer.Dial()
, and use ReadMessage()
and WriteMessage() when reading and sending messages.
method. In this way, we can flexibly conduct remote control and achieve real-time communication.
The above is the detailed content of How to use WebSocket for remote control in golang. For more information, please follow other related articles on the PHP Chinese website!