Home  >  Article  >  Backend Development  >  How to use WebSocket in golang for real-time data update

How to use WebSocket in golang for real-time data update

WBOY
WBOYOriginal
2023-12-18 09:06:451222browse

How to use WebSocket in golang for real-time data update

How to use WebSocket in Golang for real-time data updates

Overview:
WebSocket is a method for full duplex between a web browser and a server Communication technology designed for communication. In Golang, we can use net/http and github.com/gorilla/websocket in the standard library to implement WebSocket functionality. This article will introduce how to use WebSocket in Golang for real-time data updates and provide some code examples.

Steps:

Step One: Create HTTP Server
First, we need to create an HTTP server to handle WebSocket connection requests. Here is a simple example code:

package main

import (
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "index.html")
    })

    log.Println("HTTP server is starting at http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

This code creates a simple HTTP server that maps the root path ("/") to a file called index.html static files.

Step 2: Handle WebSocket connections
Next, we need to modify the code of the HTTP server so that it can handle WebSocket connection requests. We can use the github.com/gorilla/websocket library to handle WebSocket connections. The following is the modified sample code:

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

var (
    upgrader = websocket.Upgrader{
        ReadBufferSize:  1024,
        WriteBufferSize: 1024,
    }

    clients = make(map[*websocket.Conn]bool)
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "index.html")
    })

    http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
        conn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            log.Println("Failed to upgrade connection:", err)
            return
        }
        clients[conn] = true

        for {
            _, msg, err := conn.ReadMessage()
            if err != nil {
                log.Println("Failed to read message from client:", err)
                delete(clients, conn)
                break
            }

            for client := range clients {
                err := client.WriteMessage(websocket.TextMessage, msg)
                if err != nil {
                    log.Println("Failed to write message to client:", err)
                    client.Close()
                    delete(clients, conn)
                }
            }
        }
    })

    log.Println("WebSocket server is starting at ws://localhost:8080/ws")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

In this code, we create an upgrader object and define a clients variable to save all connections client. When there is a new WebSocket request, we upgrade the connection to a WebSocket connection and add it to the clients variable. Then, we read the message from the client through a loop and send the message to all connected clients.

Step 3: Create a front-end page
Finally, we need to create a front-end page to connect to the WebSocket server and display real-time data updates. The following is a simple HTML page example (index.html):

<!DOCTYPE html>
<html>

<head>
    <title>WebSocket Demo</title>
</head>

<body>
    <h1>WebSocket Demo</h1>

    <input type="text" id="message-input">
    <button onclick="send()">Send</button>

    <ul id="message-list"></ul>

    <script>
        var socket = new WebSocket("ws://localhost:8080/ws");

        socket.onmessage = function(event) {
            var message = document.createElement("li");
            message.textContent = event.data;
            document.getElementById("message-list").appendChild(message);
        };

        function send() {
            var input = document.getElementById("message-input");
            var message = input.value;
            input.value = "";

            socket.send(message);
        }
    </script>
</body>

</html>

This code creates a WebSocket connection and listens to the onmessage event when a message arrives When, add the message to a ul element for display. In addition, an input box and a send button are provided so that users can enter messages and send them to the server via WebSocket.

Summary:
Through the above steps, we can use WebSocket in Golang for real-time data updates. By creating HTTP servers, handling WebSocket connections, and interacting with front-end pages, we can achieve real-time data communication in web applications. Of course, this is just a simple example and may need to be expanded and modified according to specific needs during actual use. I hope this article was helpful and I wish you success when using WebSocket!

The above is the detailed content of How to use WebSocket in golang for real-time data update. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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