How to use WebSocket for remote control in golang

WBOY
Release: 2023-12-17 20:06:56
Original
1184 people have browsed it

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
Copy after login
  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))
}
Copy after login
  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
        }
    }
}
Copy after login
  1. Compile and run
$ go build server.go
$ go build client.go
$ ./server
$ ./client
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!