Home > Backend Development > Golang > golang Websocket tutorial: How to develop online question and answer function

golang Websocket tutorial: How to develop online question and answer function

WBOY
Release: 2023-12-02 10:14:49
Original
606 people have browsed it

golang Websocket教程:如何开发在线问答功能

golang Websocket Tutorial: How to develop online Q&A function, specific code examples are required

In today's era of developed Internet, online Q&A platform has become a platform for people to obtain knowledge and share experiences and important ways to solve problems. In order to meet users' needs for immediacy and interactivity, it is a good choice to use Websocket technology to implement online question and answer functions. This article will introduce how to use Golang to develop an online question and answer function based on Websocket, and provide specific code examples.

1. Project preparation
Before starting our tutorial, we need to do some preparations:

  1. Install Golang: First, make sure your computer has Golang installed. Please go to Golang official website to download and install.
  2. Install the necessary libraries: We will use Golang’s gorilla/websocket library to implement Websocket functionality. You can install it with the following command:
    go get github.com/gorilla/websocket
  3. Create the project directory structure: Create a new folder in your working path to store our project files.

2. Create a Websocket server
We first need to create a Websocket server to handle client connections and message delivery. Create a file named server.go in the project directory and add the following code:

package main

import (
    "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"`
    Content  string `json:"content"`
}

// 定义升级HTTP请求为Websocket的方法
var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

// 处理Websocket连接
func handleConnections(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    // 将连接的客户端添加到全局变量中
    clients[conn] = true

    for {
        var msg Message
        err := conn.ReadJSON(&msg)
        if err != nil {
            log.Printf("error: %v", err)
            delete(clients, conn)
            break
        }
        broadcast <- msg
    }
}

// 处理广播消息
func handleMessages() {
    for {
        msg := <-broadcast
        for client := range clients {
            err := client.WriteJSON(msg)
            if err != nil {
                log.Printf("error: %v", err)
                client.Close()
                delete(clients, client)
            }
        }
    }
}

func main() {
    http.HandleFunc("/ws", handleConnections)
    go handleMessages()
    log.Println("Server start on http://localhost:8000")
    log.Fatal(http.ListenAndServe(":8000", nil))
}
Copy after login

The above code implements a simple Websocket server that broadcasts client messages to all connected clients.

3. Create a Websocket client
Next, we need to create a Websocket client for users to send and receive messages on the front-end page. Create a file named client.go in the project directory and add the following code:

package main

import (
    "log"
    "net/url"
    "os"
    "os/signal"
    "time"

    "github.com/gorilla/websocket"
)

// 定义消息结构体
type Message struct {
    Username string
    Content  string
}

func main() {
    // 创建WebSocket连接
    u := url.URL{Scheme: "ws", Host: "localhost:8000", Path: "/ws"}
    c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
    if err != nil {
        log.Fatal("dial:", err)
    }
    defer c.Close()

    // 监听系统信号
    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)

    // 创建一个通道用于接收消息
    done := make(chan struct{})

    // 创建一个协程来监听用户输入并发送消息
    go func() {
        for {
            var msg Message
            err := c.ReadJSON(&msg)
            if err != nil {
                log.Println("read:", err)
                close(done)
                return
            }
            log.Printf("received: %v", msg)
        }
    }()

    // 创建一个协程来发送消息给服务器
    go func() {
        ticker := time.NewTicker(time.Second)
        defer ticker.Stop()

        for {
            select {
            case <-done:
                return
            case t := <-ticker.C:
                err := c.WriteJSON(Message{Username: "Alice", Content: "Hello, World!"})
                if err != nil {
                    log.Println("write:", err)
                    return
                }
                log.Printf("sent: %v", t.String())
            }
        }
    }()

    // 等待系统信号
    <-interrupt
    log.Println("interrupt")

    // 关闭连接
    err = c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
    if err != nil {
        log.Println("write close:", err)
    }
    select {
    case <-done:
    case <-time.After(time.Second):
    }
    log.Println("server closed")
}
Copy after login

The above code creates a Websocket client, which will send a message to the server every second and print the received news.

4. Compile and run
Open the terminal in the project directory and execute the following commands to compile and run the project:

  1. Compile server
    go build server.go
  2. Run the server
    ./server
  3. Compile the client
    go build client.go
  4. Run the client
    ./client

5. Test function
Visit http://localhost:8000 in the browser and open the console. You will see the messages sent by the client and broadcast messages from other clients. Try typing a message into the console and pressing enter, the message will be broadcast to all connected clients.

6. Summary
This tutorial introduces you how to use Golang and Websocket technology to develop a simple online question and answer function. By studying this tutorial, you should be able to understand how to create a Websocket server and client, and be able to apply related technologies in your project. I hope this tutorial can be helpful to you, and I wish you a happy learning of programming!

The above is the detailed content of golang Websocket tutorial: How to develop online question and answer function. For more information, please follow other related articles on the PHP Chinese website!

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