The following column Golang Tutorial will show you how to use websocket to implement the barrage function in Go. I hope it will be helpful to friends in need!
Using the websocket protocol, the client sends a message and the server broadcasts it to all valid connections.
Main ideas:
1. Encapsulate *websocket.conn and use the client structure to represent a client.
2. Maintain a map[client]bool, indicating a valid client mapping, used for broadcast messages
3. In addition to processing websocket connections, a broadcast coroutine must also be opened to monitor client connections and disconnect , sending a barrage incident.
Recommended: "go Language Tutorial"
Main structure:
type Client struct{ wsConnect *websocket.Conn inChan chan []byte outChan chan []byte closeChan chan byte Name string //客户的名称 Id string //客户id,唯一 mutex sync.Mutex // 对closeChan关闭上锁 IsClosed bool // 防止closeChan被关闭多次 } type Message struct { EventType byte `json:"type"` // 0表示用户发布消息;1表示用户进入;2表示用户退出 Name string `json:"name"` // 用户名称 Message string `json:"message"` // 消息内容 } clients = make(map [*util.Client] bool) // 用户组映射 join = make(chan *util.Client, 10) // 用户加入通道 leave = make(chan *util.Client, 10) // 用户退出通道 message = make(chan Message, 10) // 消息通道
server-side code
package main import ( "encoding/json" "fmt" "github.com/gorilla/websocket" "goGin/server/util" "net/http" ) var( upgrader = websocket.Upgrader{ // 允许跨域 CheckOrigin:func(r *http.Request) bool{ return true }, } clients = make(map [*util.Client] bool) // 用户组映射 join = make(chan *util.Client, 10) // 用户加入通道 leave = make(chan *util.Client, 10) // 用户退出通道 message = make(chan Message, 10) // 消息通道 ) type Message struct { EventType byte `json:"type"` // 0表示用户发布消息;1表示用户进入;2表示用户退出 Name string `json:"name"` // 用户名称 Message string `json:"message"` // 消息内容 } func wsHandler(w http.ResponseWriter , r *http.Request){ var( wsConn *websocket.Conn err error client *util.Client data []byte ) r.ParseForm() //返回一个map,并且赋值给r.Form name := r.Form["name"][0] id := r.Form["id"][0] if wsConn , err = upgrader.Upgrade(w,r,nil); err != nil{ return } if client , err = util.InitConnection(wsConn); err != nil{ goto ERR } client.Id = id client.Name = name // 如果用户列表中没有该用户 if !clients[client] { join <- client } for { if data , err = client.ReadMessage();err != nil{ //一直读消息,没有消息就阻塞 goto ERR } var msg Message msg.EventType = 0 msg.Name = client.Name msg.Message = string(data) message <- msg } ERR: leave<-client//这个客户断开 client.Close() } func broadcaster() { for { select { // 消息通道中有消息则执行,否则堵塞 case msg := <-message: // 将数据编码成json形式,data是[]byte类型 // json.Marshal()只会编码结构体中公开的属性(即大写字母开头的属性) data, err := json.Marshal(msg) if err != nil { return } for client := range clients { if client.IsClosed == true { leave<-client//这个客户断开 continue } // fmt.Println("=======the json message is", string(data)) // 转换成字符串类型便于查看 if client.WriteMessage(data) != nil { continue //发送失败就跳过 } } // 有用户加入 case client := <-join: clients[client] = true // 将用户加入映射 // 将用户加入消息放入消息通道 var msg Message msg.Name = client.Name msg.EventType = 1 msg.Message = fmt.Sprintf("%s join in, there are %d preson in room", client.Name, len(clients)) message <- msg // 有用户退出 case client := <-leave: // 如果该用户已经被删除 if !clients[client] { break } delete(clients, client) // 将用户从映射中删除 // 将用户退出消息放入消息通道 var msg Message msg.Name = client.Name msg.EventType = 2 msg.Message = fmt.Sprintf("%s leave, there are %d preson in room", client.Name, len(clients)) message <- msg } } } func main(){ go broadcaster() http.HandleFunc("/ws",wsHandler) http.ListenAndServe("0.0.0.0:7777",nil) }
Encapsulation client
package util import ( "github.com/gorilla/websocket" "sync" "errors" ) type Client struct{ wsConnect *websocket.Conn inChan chan []byte outChan chan []byte closeChan chan byte Name string //客户的名称 Id string //客户id,唯一 mutex sync.Mutex // 对closeChan关闭上锁 IsClosed bool // 防止closeChan被关闭多次 } func InitConnection(wsConn *websocket.Conn)(conn *Client ,err error){ conn = &Client{ wsConnect:wsConn, inChan: make(chan []byte,1000), outChan: make(chan []byte,1000), closeChan: make(chan byte,1), IsClosed:false, } // 启动读协程 go conn.readLoop(); // 启动写协程 go conn.writeLoop(); return } func (conn *Client)ReadMessage()(data []byte , err error){ select{ case data = <- conn.inChan: case <- conn.closeChan: err = errors.New("connection is closeed") } return } func (conn *Client)WriteMessage(data []byte)(err error){ select{ case conn.outChan <- data: case <- conn.closeChan: err = errors.New("connection is closeed") } return } func (conn *Client)Close(){ // 线程安全,可多次调用 conn.wsConnect.Close() // 利用标记,让closeChan只关闭一次 conn.mutex.Lock() if !conn.IsClosed { close(conn.closeChan) conn.IsClosed = true } conn.mutex.Unlock() } func (conn *Client)readLoop(){ var( data []byte err error ) for{ if _, data , err = conn.wsConnect.ReadMessage(); err != nil{ goto ERR } //阻塞在这里,等待inChan有空闲位置 select{ case conn.inChan <- data: case <- conn.closeChan: // closeChan 感知 conn断开 goto ERR } } ERR: conn.Close() } func (conn *Client)writeLoop(){ var( data []byte err error ) for{ select{ case data= <- conn.outChan: case <- conn.closeChan: goto ERR } if err = conn.wsConnect.WriteMessage(websocket.TextMessage , data); err != nil{ goto ERR } } ERR: conn.Close() }
Client code
<!DOCTYPE html> <html> <head> <title>go websocket</title> <meta charset="utf-8" /> </head> <body> <script type="text/javascript"> var wsUri ="ws://127.0.0.1:7777/ws?name=aaa&id=112"; var output; function init() { output = document.getElementById("output"); testWebSocket(); } function testWebSocket() { websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onclose = function(evt) { onClose(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; } function onOpen(evt) { writeToScreen("CONNECTED"); // doSend("WebSocket rocks"); } function onClose(evt) { writeToScreen("DISCONNECTED"); } function onMessage(evt) { writeToScreen('<span style="color: blue;">RESPONSE: '+ evt.data+'</span>'); // websocket.close(); } function onError(evt) { writeToScreen('<span style="color: red;">ERROR:</span> '+ evt.data); } function doSend(message) { // writeToScreen("SENT: " + message); websocket.send(message); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; output.appendChild(pre); } window.addEventListener("load", init, false); function sendBtnClick(){ var msg = document.getElementById("input").value; doSend(msg); document.getElementById("input").value = ''; } function closeBtnClick(){ websocket.close(); } </script> <h2 id="WebSocket-nbsp-Test">WebSocket Test</h2> <input type="text" id="input"></input> <button onclick="sendBtnClick()" >send</button> <button onclick="closeBtnClick()" >close</button> <div id="output"></div> </body> </html>
The above is the detailed content of How Go uses websocket to implement barrage function. For more information, please follow other related articles on the PHP Chinese website!

Golang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

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 excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

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.

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.