How to implement websocket in golang

PHPz
Release: 2023-03-29 13:46:39
Original
1869 people have browsed it

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!

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