Golang development: using Websocket to implement real-time chat application

WBOY
Release: 2023-09-20 13:15:28
Original
759 people have browsed it

Golang development: using Websocket to implement real-time chat application

Golang development: Real-time chat application using Websocket

In today's Internet era, real-time communication has become an indispensable part of people's lives. Whether it is instant messaging, real-time chat or real-time updates, an efficient and stable communication method is required to achieve it. Websocket is a protocol that is very suitable for real-time communication.

Golang is a simple and efficient programming language with excellent concurrency performance and is very suitable for developing real-time communication applications. This article will introduce how to use Golang's Websocket library to implement a real-time chat application and provide corresponding code examples.

First, we need to create a Golang project and introduce Golang's Websocket library.

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)
Copy after login

Next, we need to define some global variables and structures.

var clients = make(map[*websocket.Conn]bool) // 客户端集合
var broadcast = make(chan Message)           // 广播消息通道

// 消息结构体
type Message struct {
    Username string `json:"username"`
    Message  string `json:"message"`
}
Copy after login

Then, we need to implement a function that handles Websocket connections.

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

    // 将连接添加到客户端集合中
    clients[conn] = true

    // 关闭连接时,从客户端集合中移除
    defer func() {
        delete(clients, conn)
        conn.Close()
    }()

    // 循环接收和发送消息
    for {
        var message Message
        err := conn.ReadJSON(&message)
        if err != nil {
            log.Printf("error: %v", err)
            delete(clients, conn)
            break
        }
        broadcast <- message
    }
}
Copy after login

Next, we need to implement a function that broadcasts the message to all clients.

func broadcastMessages() {
    for {
        // 从广播通道中接收消息
        message := <-broadcast

        // 将消息发送给所有客户端
        for client := range clients {
            err := client.WriteJSON(message)
            if err != nil {
                log.Printf("error: %v", err)
                client.Close()
                delete(clients, client)
            }
        }
    }
}
Copy after login

Finally, we need to start the Websocket server in the main function.

func main() {
    // 设置静态文件目录
    fs := http.FileServer(http.Dir("public"))
    http.Handle("/", fs)

    // 设置Websocket路由
    http.HandleFunc("/ws", handleWebSocket)

    // 启动Websocket服务器
    go broadcastMessages()

    // 开始监听端口
    log.Println("Server started on :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal(err)
    }
}
Copy after login

Next, we can create an HTML page to implement the user interface.

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>实时聊天应用</title>
</head>

<body>
  <h1>实时聊天应用</h1>
  
  <div id="message-container"></div>
  
  <form>
    <input type="text" id="username" placeholder="请输入用户名">
    <input type="text" id="message" placeholder="请输入消息">
    <button type="button" onclick="sendMessage()">发送</button>
  </form>

  <script>
    // 创建Websocket连接
    var socket = new WebSocket("ws://localhost:8080/ws");
    
    // 监听连接事件
    socket.onopen = function() {
      console.log("连接成功");
    };
    
    // 监听消息事件
    socket.onmessage = function(event) {
      var message = JSON.parse(event.data);
      var username = message.username;
      var content = message.message;
      var container = document.getElementById("message-container");
      container.innerHTML += "<p><b>" + username + ":</b>" + content + "</p>";
    };
    
    // 监听错误事件
    socket.onerror = function(error) {
      console.log("出现错误:" + error);
    }
    
    // 监听关闭事件
    socket.onclose = function(event) {
      console.log("连接关闭");
    }
    
    // 发送消息
    function sendMessage() {
      var username = document.getElementById("username").value;
      var message = document.getElementById("message").value;
      if (username && message) {
        var data = {
          username: username,
          message: message
        };
        socket.send(JSON.stringify(data));
        document.getElementById("message").value = "";
      }
    }
  </script>
</body>

</html>
Copy after login

So far, we have completed an example of using Golang's Websocket library to implement a real-time chat application. Through this example, we can deeply understand the working principle of Websocket and learn how to use Golang to develop real-time communication applications.

Of course, there are many details and security considerations in actual projects, such as verifying messages, using SSL encryption, etc. But with this example, you already have a good starting point for building your own live chat application. Happy coding!

The above is the detailed content of Golang development: using Websocket to implement real-time chat application. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!