Home >Backend Development >Golang >golang WebSocket example: building a simple chat application

golang WebSocket example: building a simple chat application

WBOY
WBOYOriginal
2023-12-18 08:13:311205browse

golang WebSocket示例:构建一个简单的聊天应用

Golang WebSocket Example: Building a Simple Chat Application

With the development of the Internet, real-time communication has attracted more and more attention. As a real-time communication protocol, WebSocket can establish a persistent connection between the client and the server, making two-way real-time data transmission possible. This article will introduce how to use Golang to build a simple chat application to send and receive real-time messages through WebSocket.

Before starting, make sure you have correctly installed the Golang development environment on your computer.

First, we need to import the "Gorilla Websocket" package, which is a commonly used WebSocket library in Golang. Install using the following command in the terminal:

go get github.com/gorilla/websocket

Next, we create a main.go file and import the required packages:

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

In the main function, we define a WebSocket processor Function, used to handle WebSocket connection requests from the client:

func wsHandler(w http.ResponseWriter, r *http.Request) {
    // 升级HTTP连接为WebSocket连接
    conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
    if err != nil {
        log.Println(err)
        return
    }

    // 处理WebSocket连接
    for {
        // 读取客户端发送的消息
        _, msg, err := conn.ReadMessage()
        if err != nil {
            log.Println(err)
            break
        }

        // 将消息发送给所有连接的客户端
        for client := range clients {
            err := client.WriteMessage(websocket.TextMessage, msg)
            if err != nil {
                log.Println(err)
                client.Close()
                delete(clients, client)
            }
        }
    }

    // 关闭WebSocket连接
    conn.Close()
}

In the above code, we first upgrade the HTTP connection to a WebSocket connection, and then use a for loop to continuously receive messages sent by the client, and These messages are sent to all connected clients. When an error occurs or the client disconnects, we close the corresponding connection.

Next, we need to define a global variable clients to save all connected clients:

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

Then, we modify the code in the main function and connect the WebSocket processor function with "/ws "Associate the path and start an HTTP server:

func main() {
    http.HandleFunc("/ws", wsHandler)

    err := http.ListenAndServe(":8000", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

Finally, we can use a browser or WebSocket client tool to test our chat application. Enter "http://localhost:8000" in the browser, open the console, and execute the following JavaScript code:

var ws = new WebSocket("ws://localhost:8000/ws");

// 连接建立时触发的事件
ws.onopen = function() {
    console.log("连接成功");
};

// 收到消息时触发的事件
ws.onmessage = function(evt) {
    console.log("收到消息:" + evt.data);
};

// 发送消息
ws.send("Hello, World!");

Through the above code, we will receive "Hello, World!" from the server. message and output it in the console.

So far, we have successfully built a simple chat application that uses Golang and WebSocket to send and receive real-time messages. Of course, this is just a basic example and you can extend and optimize it according to your own needs. I hope this article is helpful to you, and I wish you more success when developing real-time communication applications using Golang and WebSocket!

The above is the detailed content of golang WebSocket example: building a simple chat application. 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