How does Go WebSocket implement two-way communication?

WBOY
Release: 2024-06-05 21:38:00
Original
1070 people have browsed it

The Go language has built-in support for WebSocket, which can achieve two-way communication through the following steps: Create a WebSocket server: Create an HTTP handler function. Create an Upgrader structure to upgrade the HTTP request. Start the WebSocket server. Create a WebSocket client: Create an HTTP request and set the WebSocket headers. Create a Dialer structure. Use the Dial method to establish a connection.

Go WebSocket 如何实现双向通信?

Go WebSocket: Implementing two-way communication

WebSocket is a two-way communication protocol that allows the client and server to communicate in a single persistent Real-time data exchange over TCP connections. The Go language provides developers with built-in support for WebSocket, making bidirectional communication simple and straightforward.

Creating a WebSocket server

Creating a WebSocket server requires three steps:

  1. Use the net/http package Create the http.Handler function that handles WebSocket connections.
  2. Create a websocket.Upgrader structure that upgrades HTTP requests to WebSocket connections.
  3. Use the http.ServeHTTP method to start the WebSocket server.
package main

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

func main() {
    // HTTP 处理程序
    handler := func(w http.ResponseWriter, r *http.Request) {
        upgrader := websocket.Upgrader{}
        conn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            log.Fatal(err)
        }
        defer conn.Close()

        for {
            messageType, message, err := conn.ReadMessage()
            if err != nil {
                log.Fatal(err)
            }
            if messageType == websocket.CloseMessage {
                log.Println("Client closed connection")
                return
            }
            log.Printf("Received from client: %s", string(message))
            err = conn.WriteMessage(messageType, []byte("Echoed: "+string(message)))
            if err != nil {
                log.Fatal(err)
            }
        }
    }

    // 启动 WebSocket 服务端
    http.HandleFunc("/websocket", handler)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal(err)
    }
}
Copy after login

Creating a WebSocket client

Creating a WebSocket client also requires three steps:

  1. Use net/ The http package creates http.Request and sets the "Upgrade: WebSocket" header.
  2. Create a websocket.Dialer structure, which is used to establish a WebSocket connection.
  3. Use the Dial method to establish a connection.
package main

import (
    "fmt"
    "log"

    "github.com/gorilla/websocket"
)

func main() {
    dialers := websocket.Dialer{
        ReadBufferSize:  1024,
        WriteBufferSize: 1024,
    }

    conn, _, err := dialers.Dial("ws://localhost:8080/websocket", nil)
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    for i := 0; i < 10; i++ {
        message := fmt.Sprintf("Hello from client %d", i)
        err := conn.WriteMessage(websocket.TextMessage, []byte(message))
        if err != nil {
            log.Fatal(err)
        }

        _, message, err = conn.ReadMessage()
        if err != nil {
            log.Fatal(err)
        }
        log.Printf("Received echo: %s", string(message))
    }
}
Copy after login

With these steps, you can easily implement WebSocket two-way communication in Go, adding real-time interaction capabilities to your applications.

The above is the detailed content of How does Go WebSocket implement two-way communication?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
go
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!