Home >Backend Development >Golang >How to use WebSocket for remote control in golang

How to use WebSocket for remote control in golang

WBOY
WBOYOriginal
2023-12-17 20:06:561213browse

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:

  1. Introduce dependency packages
go get github.com/gorilla/websocket
  1. Create WebSocket server
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))
}
  1. Create WebSocket client
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
        }
    }
}
  1. Compile and run
$ 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!

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