


golang Websocket tutorial: How to develop online question and answer function
Dec 02, 2023 am 10:14 AMgolang 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:
- Install Golang: First, make sure your computer has Golang installed. Please go to Golang official website to download and install.
- 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 - 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)) }
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() { // 創(chuàng)建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() // 監(jiān)聽系統(tǒng)信號 interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) // 創(chuàng)建一個通道用于接收消息 done := make(chan struct{}) // 創(chuàng)建一個協(xié)程來監(jiān)聽用戶輸入并發(fā)送消息 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) } }() // 創(chuàng)建一個協(xié)程來發(fā)送消息給服務器 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()) } } }() // 等待系統(tǒng)信號 <-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") }
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:
- Compile server
go build server.go - Run the server
./server - Compile the client
go build client.go - 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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

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

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.
