Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the function of websocket chat Room by golang

Shulou Source: shulou.com Published: 2022-06-03 07:58:29 10月17日 Update

This article will explain in detail how golang realizes the function of websocket chat room. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Basic principles:

1. The golang.org/x/net/websocket package is introduced.

two。 Listen on the port.

3. When the client connects, send the structure: {"type": "login", "uid": "I am the user name", "msg": "login succeeded"}'. The server maintains a map according to the login information, which is used to store the connectors of different users.

4. When a user speaks, a poll of msg content is sent to a user.

5. The client uses the js websocket function as the client to start chatting.

Deficiency: only distinguish users according to the uid transmitted by the client, there is no identity verification, but for a demo, it is not necessary.

Server Code:

Package main import ("encoding/json", "fmt", "golang.org/x/net/websocket", "log", "net/http") / ProxyConfig configuration type MsgConfig struct {Type string `json: "type,omitempty" `Uid string `json: "uid,omitempty" `Msg string `json: "msg Omitempty "`} var connMap = make (map [string] * websocket.Conn) func Echo (ws * websocket.Conn) {var err error for {var reply string if err = websocket.Message.Receive (ws, & reply) Err! = nil {fmt.Println ("Can't receive") break} replyMsg: = MsgConfig {} json.Unmarshal ([] byte (reply)) & replyMsg) if replyMsg.Type = = "login" & & replyMsg.Uid! = "" {connMap [replyMsg.Uid] = ws fmt.Println (connMap)} for k, v: = range connMap {go sendMessage (replyMsg, v) K)} func sendMessage (replyMsg MsgConfig, conn * websocket.Conn ConnUid string) {msg: = replyMsg.Uid + "say:" + replyMsg.Msg if connUid = = replyMsg.Uid {fmt.Println (msg) if replyMsg.Type = = "login" {msg = "login successful"} else {msg = "you say:" + replyMsg.Msg }} if err: = websocket.Message.Send (conn Msg) Err! = nil {fmt.Println ("Can't send")}} func main () {http.Handle ("/", websocket.Handler (Echo)) if err: = http.ListenAndServe (": 1234", nil); err! = nil {log.Fatal ("ListenAndServe:", err)}}

Client chat:

You can enter the following code in the browser console to chat:

/ / ip:port is set to your own

Ws = new WebSocket ("ws://127.0.0.1:1234"); ws.onopen = function (ev) {ws.send ('{"type": "login", "uid": "I am the user name", "msg": "I logged in"}');}; ws.onmessage = function (ev) {if (ev.data) {console.log (ev.data)}} / / the following sentence can be sent multiple times as a chat. Ws.send ('{"type": "msg", "uid": "I am the user name", "msg": "Hello"}')

Client effect picture:

Server effect picture:

This is the end of the article on "how golang realizes the function of websocket chat room". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: User customer client feature user name article login chat room success code content effect effect more service different good practical necessary hello Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi MySQL NVidia Shulou Tech Info Microsoft