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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

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 do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How do I write mock objects and stubs for testing in Go? How do I write mock objects and stubs for testing in Go? Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How can I define custom type constraints for generics in Go? How can I define custom type constraints for generics in Go? Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

How can I use tracing tools to understand the execution flow of my Go applications? How can I use tracing tools to understand the execution flow of my Go applications? Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications? Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications? Mar 25, 2025 am 11:17 AM

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

How do you use table-driven tests in Go? How do you use table-driven tests in Go? Mar 21, 2025 pm 06:35 PM

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

How do you specify dependencies in your go.mod file? How do you specify dependencies in your go.mod file? Mar 27, 2025 pm 07:14 PM

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.

See all articles