Home Backend Development Golang golang Websocket Development Guide: Implementing multi-person online collaboration function

golang Websocket Development Guide: Implementing multi-person online collaboration function

Dec 02, 2023 pm 12:18 PM
golang websocket Multiplayer online

golang Websocket开发指南:实现多人在线协作功能

Golang Websocket Development Guide: Implementing multi-person online collaboration function

Introduction:
Websocket is a method that establishes a persistent connection between the client and the server Communication protocol, which can realize the function of the server actively pushing messages to the client. In practical applications, Websocket is widely used in real-time notifications, chat rooms, multi-person online collaboration and other scenarios. This article will introduce how to use Golang to develop Websocket applications, and combine it with code examples to demonstrate how to implement multi-person online collaboration.

1. Introduction to Golang Websocket
Golang comes with a built-in Websocket library to facilitate developers to quickly build Websocket applications. Using Golang's Websocket library, you can easily implement Websocket functions such as connection, message sending and receiving, and connection pool management.

2. Golang Websocket development environment configuration

  1. Install Golang development environment
  2. Install Golang Websocket library

    • Open the terminal Or command line window
    • Execute the command: go get github.com/gorilla/websocket

3. Golang Websocket development process

  1. Import the required libraries
    Import the "golang.org/x/net/websocket" and "github.com/gorilla/websocket" libraries at the beginning of the code.
  2. Define connection pool
    The subsequent sample code will use a global connection pool to manage the Websocket connections of all clients to achieve the function of multi-person online collaboration. Define a connection pool of structure type. The fields in the structure include a mutex and a slice to store the connection.

    type ConnPool struct {
        connLock sync.Mutex
        conns    []*websocket.Conn
    }
    Copy after login
  3. Handling WebSocket requests
    In Golang, HTTP requests can be monitored and processed through the Http package. We need to write a function that handles Websocket requests and register the function in the HTTP server.

    func wsHandler(w http.ResponseWriter, r *http.Request) {
        conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
        if err != nil {
            log.Println("websocket upgrade failed:", err)
            return
        }
    
        // 将连接添加到连接池中
        pool.add(conn)
        
        // 具体的消息处理逻辑
        go handleMessages(conn)
    }
    Copy after login
  4. Message processing logic
    In the sample code, we use a goroutine to handle the sending and receiving of messages for each connection. By reading messages on the connection, multiple people can collaborate online. When a new message is sent, all connections are traversed through the connection pool and the message is sent.

    func handleMessages(conn *websocket.Conn) {
        for {
            message := ""
            err := conn.ReadJSON(&message)
            if err != nil {
                log.Println("read message failed:", err)
                // 从连接池中删除连接
                pool.remove(conn)
                break
            }
            
            // 遍历连接池,广播消息
            pool.broadcast(message)
        }
    }
    Copy after login
  5. Start the Websocket server
    Write a function to start the Websocket server. In this function, we need to create an Http server instance and bind the function that handles Websocket requests.

    func startServer() {
        http.HandleFunc("/ws", wsHandler)
        http.ListenAndServe(":8000", nil)
    }
    Copy after login
  6. Complete sample code
    The following is the complete Websocket application sample code:

    package main
    
    import (
        "log"
        "net/http"
        "sync"
    
        "github.com/gorilla/websocket"
    )
    
    type ConnPool struct {
        connLock sync.Mutex
        conns    []*websocket.Conn
    }
    
    var pool ConnPool
    
    func (p *ConnPool) add(conn *websocket.Conn) {
        p.connLock.Lock()
        defer p.connLock.Unlock()
    
        p.conns = append(p.conns, conn)
    }
    
    func (p *ConnPool) remove(conn *websocket.Conn) {
        p.connLock.Lock()
        defer p.connLock.Unlock()
    
        newConns := make([]*websocket.Conn, 0, len(p.conns)-1)
        for _, c := range p.conns {
            if c != conn {
                newConns = append(newConns, c)
            }
        }
    
        p.conns = newConns
    }
    
    func (p *ConnPool) broadcast(message string) {
        p.connLock.Lock()
        defer p.connLock.Unlock()
    
        for _, conn := range p.conns {
            err := conn.WriteJSON(message)
            if err != nil {
                log.Println("write message failed:", err)
            }
        }
    }
    
    func wsHandler(w http.ResponseWriter, r *http.Request) {
        conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
        if err != nil {
            log.Println("websocket upgrade failed:", err)
            return
        }
    
        pool.add(conn)
        go handleMessages(conn)
    }
    
    func handleMessages(conn *websocket.Conn) {
        for {
            message := ""
            err := conn.ReadJSON(&message)
            if err != nil {
                log.Println("read message failed:", err)
                pool.remove(conn)
                break
            }
    
            pool.broadcast(message)
        }
    }
    
    func startServer() {
        http.HandleFunc("/ws", wsHandler)
        http.ListenAndServe(":8000", nil)
    }
    
    func main() {
        startServer()
    }
    Copy after login

4. Run the example

  1. Compile and run the sample code:

    go build main.go
    ./main
    Copy after login
  2. Open the browser and visit localhost:8000 to enter the Websocket application page.
  3. Open this page in multiple browser windows to demonstrate the function of multi-person online collaboration. After you enter a message in any window, the other windows receive the message.

Conclusion:
This article introduces how to use Golang to develop Websocket applications, and through specific code examples, shows how to realize the function of multi-person online collaboration. I hope this article will help you understand and use Golang Websocket!

The above is the detailed content of golang Websocket Development Guide: Implementing multi-person online collaboration function. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

How to find the first substring matched by a Golang regular expression? How to find the first substring matched by a Golang regular expression? Jun 06, 2024 am 10:51 AM

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to use predefined time zone with Golang? How to use predefined time zone with Golang? Jun 06, 2024 pm 01:02 PM

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

See all articles