Home Backend Development Golang How to implement websocket in golang

How to implement websocket in golang

Mar 29, 2023 am 11:26 AM

In an era when modern front-ends pay more and more attention to real-time and interactivity, a network communication protocol has become more popular, which is WebSocket. In use, WebSocket and HTTP have certain similarities, but unlike traditional HTTP requests, WebSocket can maintain connections for a long time. If you are considering using WebSocket to build a web application, then you may need to use some programming language to implement it. Among them, Golang is one of the very popular programming languages. Let us learn how to implement WebSocket in Golang.

1. What is WebSocket?

WebSocket is a network protocol that provides two-way communication over a single TCP connection. In the traditional HTTP protocol, the request is sent from the browser to the server, and the server processes it and returns the result to the browser. This process is a one-time process. After the request processing is completed, the connection will be closed. The WebSocket protocol is different. When the browser establishes a connection with the server, the connection will be maintained until the user or the server decides to close the connection. This means that the server can send information to the client at any time while the connection is maintained without waiting for the browser to make a request.

2. Golang implements WebSocket

Golang is a programming language that supports concurrent programming. It was originally developed by Google. Its advantage lies in its operating efficiency and extremely low memory usage. Below we will introduce how to implement WebSocket using Golang.

  1. Install the Gorilla WebSocket library
    Gorilla WebSocket is a popular WebSocket library that provides a simple and easy-to-use API for creating and handling WebSocket connections. Before installing the Gorilla WebSocket library, you need to install the Go environment first. After the Go installation is complete, use the following command to install the Gorilla WebSocket library:

    go get github.com/gorilla/websocket
    Copy after login
  2. Write code

Below we will use Go and the Gorilla WebSocket library to implement a simple chat room. In our chat rooms, users can send messages and view messages from other users. The following is the code to implement a WebSocket chat room:

package main

import (
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/websocket"
)

var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan Message)
var upgrader = websocket.Upgrader{}

// Message struct
type Message struct {
    Username string `json:"username"`
    Body     string `json:"body"`
}

func main() {
    // Configure websocket route
    http.HandleFunc("/ws", handleConnections)

    // Start listening for incoming chat messages
    go handleMessages()

    // Start the server on localhost port 8080 and log any errors
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
    // Upgrade initial GET request to a websocket
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Fatal(err)
    }
    // Make sure we close the connection when the function returns
    defer ws.Close()

    // Register our new client
    clients[ws] = true

    for {
        var msg Message
        // Read in a new message as JSON and map it to a Message object
        err := ws.ReadJSON(&msg)
        if err != nil {
            log.Printf("error: %v", err)
            delete(clients, ws)
            break
        }
        // Send the newly received message to the broadcast channel
        broadcast <- msg
    }
}

func handleMessages() {
    for {
        // Grab the next message from the broadcast channel
        msg := <-broadcast
        // Send it out to every client that is currently connected
        for client := range clients {
            err := client.WriteJSON(msg)
            if err != nil {
                log.Printf("error: %v", err)
                client.Close()
                delete(clients, client)
            }
        }
    }
}
Copy after login

The main idea of ​​the code is to create a WebSocket connection and add it to the clients list, and any messages will be written to broadcast channel and sent to all clients in another goroutine. Each connection receives messages by reading and allocating Message objects. The sample code for the client to send a message is as follows:

let socket = new WebSocket("ws://localhost:8080/ws");

socket.addEventListener("open", function() {
  socket.send(JSON.stringify({
    "username": "John",
    "body": "Hello World!"
  }));
});

socket.addEventListener("message", function(event) {
  console.log("Received: " + event.data);
});
Copy after login

In this example, we first create a WebSocket object and connect it to the server. After the connection is successful, we send a JSON as the message body. When the server sends a message to the client, we need to listen to the message event in the client's JavaScript code and process it when the message is received.

3. Summary

WebSocket provides a new way of real-time communication, which provides more interactivity and user experience for web applications. Using the Golang and Gorilla WebSocket libraries you can easily implement WebSocket connections and use the WebSocket protocol in your applications.

This article provides a simple chat room implementation example, I hope it will be helpful to you. Of course, WebSocket can be used in many other types of applications, so adapt it to your own needs.

The above is the detailed content of How to implement websocket in golang. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

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 specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

See all articles