Home  >  Article  >  Backend Development  >  How to develop Websocket chat room using Go language

How to develop Websocket chat room using Go language

PHPz
PHPzOriginal
2023-12-14 13:46:50844browse

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)
            }
        }
    }
}

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

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

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