Table of Contents
Websocket 聊天室
Home Backend Development Golang How to develop Websocket chat room using Go language

How to develop Websocket chat room using Go language

Dec 14, 2023 pm 01:46 PM
go language websocket chatroom

How to develop Websocket chat room using Go language

How to use Go language to develop Websocket chat room

Websocket is a real-time communication protocol that enables two-way communication between the server and the client by establishing a connection. . Websocket is a very good choice when developing chat rooms because it enables real-time message exchange and provides efficient performance. This article will introduce how to develop a simple Websocket chat room using Go language and provide some specific code examples.

1. Preparation work

1. Install the Go language environment

Before starting, you first need to install the Go language environment. The official website of Go language (https://golang.org/) provides installation packages for each platform, which can be downloaded and installed according to your own operating system.

2. Install the websocket library

In the Go language, use the "github.com/gorilla/websocket" package to provide WebSocket-related functions. You can install the package through the following command:

go get github.com/gorilla/websocket

2. Create a chat room server

First, we need to create a simple Server, used to handle the establishment of Websocket connections and the sending and receiving of messages.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

var clients = make(map[*websocket.Conn]bool) // 存储连接的客户端
var broadcast = make(chan Message)           // 消息广播通道

// 定义消息结构体
type Message struct {
    Username string `json:"username"`
    Message  string `json:"message"`
}

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

    go handleMessages()

    // 启动服务器
    log.Println("服务器启动,监听端口:8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
    // 升级HTTP连接为Websocket连接
    ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
    if err != nil {
        log.Fatal(err)
    }

    // 关闭连接
    defer ws.Close()

    // 将客户端连接添加到clients映射中
    clients[ws] = true

    for {
        var msg Message
        // 读取客户端发送的消息
        err := ws.ReadJSON(&msg)
        if err != nil {
            log.Printf("读取消息错误:%v", err)
            delete(clients, ws)
            break
        }

        // 将接收到的消息放入广播通道中
        broadcast <- msg
    }
}

func handleMessages() {
    for {
        // 从广播通道中读取消息
        msg := <-broadcast

        // 遍历所有连接的客户端,将消息发送给每个客户端
        for client := range clients {
            err := client.WriteJSON(msg)
            if err != nil {
                log.Printf("发送消息错误:%v", err)
                client.Close()
                delete(clients, client)
            }
        }
    }
}
Copy after login

The above code creates a simple Websocket chat room server. In the handleConnections function, we put the received message into the broadcast channel. handleMessagesThe function reads messages from the broadcast channel and sends the messages to all connected clients.

3. Create a front-end interface

Next, we need to create a front-end interface for users to enter user names and messages, and display chat content in real time.

<!doctype html>
<html>

<head>
  <title>Websocket 聊天室</title>
  
  <style>
    #message-box {
      height: 500px;
      overflow-y: scroll;
    }
  </style>
</head>

<body>
  <h1 id="Websocket-聊天室">Websocket 聊天室</h1>

  <div id="message-box"></div>

  <form id="message-form" onsubmit="sendMessage(event)">
    <input type="text" id="username" placeholder="请输入用户名" required>
    <br />
    <input type="text" id="message" placeholder="请输入消息" required>
    <br />
    <button type="submit">发送</button>
  </form>

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

    socket.onmessage = function (event) {
      const data = JSON.parse(event.data);
      const messageBox = document.getElementById("message-box");
      const messageElement = document.createElement("p");
      messageElement.innerText = data.username + ": " + data.message;
      messageBox.appendChild(messageElement);
    };

    function sendMessage(event) {
      event.preventDefault();

      const username = document.getElementById("username").value;
      const message = document.getElementById("message").value;

      const data = {
        username: username,
        message: message
      };

      socket.send(JSON.stringify(data));
      document.getElementById("message").value = "";
    }
  </script>
</body>

</html>
Copy after login

The above code creates a simple HTML interface, including a username input box, a message input box and a send button. Process the received message through socket.onmessage and display the message in the message box. Send the input message via socket.send.

4. Run the program

Enter the project directory in the terminal and execute the following command to start the server:

go run main.go
Copy after login

Then, open index.html# in the browser ## page, enter the user name and message, and click Send.

Through the above steps, we successfully developed a simple Websocket chat room using Go language. In actual development, more functions can be added, such as chat records, private messages, etc. I hope this article can help you understand and learn Go language to develop Websocket chat rooms.

The above is the detailed content of How to develop Websocket chat room using Go language. 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 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. �...

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...

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...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

See all articles