Golang一对一聊天 [英] Golang one to one chat
本文介绍了Golang一对一聊天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在golang上进行一对一的聊天,我发现这个带有websocket的简单脚本非常有效,它是一个拥有多少用户的房间。但我想将它转换为像facebook一样一个这是脚本如果有人可以帮助,因为我不知道我需要使用更多的连接或筛选用户。
I want make one to one chat on golang and I find this simple script with websocket it work really well and it is one room with how much users inside you want. But I want convert it to one to one like facebook this is script if someone can help because I dont know am I need use more connections or filter users.
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
var clients = make(map[*websocket.Conn]bool) // connected clients
var broadcast = make(chan Message) // broadcast channel
// Configure the upgrader
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// Define our message object
type Message struct {
Email string `json:"email"`
Username string `json:"username"`
Message string `json:"message"`
Created string `json:"created"`
}
func main() {
// Create a simple file server
fs := http.FileServer(http.Dir("public"))
http.Handle("/", fs)
// Configure websocket route
http.HandleFunc("/ws", handleConnections)
// Start listening for incoming chat messages
go handleMessages()
// Start the server on localhost port 8000 and log any errors
log.Println("http server started on :8090")
err := http.ListenAndServe(":8090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
// Upgrade initial GET request to a websocket
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
// Make sure we close the connection when the function returns
defer ws.Close()
// Register our new client
clients[ws] = true
for {
var msg Message
// Read in a new message as JSON and map it to a Message object
err := ws.ReadJSON(&msg)
if err != nil {
log.Printf("error: %v", err)
delete(clients, ws)
break
}
// Send the newly received message to the broadcast channel
broadcast <- msg
}
}
func handleMessages() {
for {
// Grab the next message from the broadcast channel
msg := <-broadcast
// Send it out to every client that is currently connected
for client := range clients {
err := client.WriteJSON(msg)
if err != nil {
log.Printf("error: %v", err)
client.Close()
delete(clients, client)
}
}
}
}
我是否需要更改此部分
clients[ws] = true
推荐答案
您需要做很少的事情:
- 摆脱
广播
频道 li>
- 不知何故,放大器;从请求中获取您的用户想要连接的客户端。一些房间号/名称,密码?例如URL参数
/ ws?chat = abc
。您可能需要维护一个map [chatid] [] * websocket.Conn
- 匹配2(或更多)客户端。
- 维护一个映射,可能类型为
map [* websocket.Conn] * websocket.Conn
- 从客户端接收到消息后查找地图并将消息发送给匹配的客户端。类似于
handleMessages()
中的方式,但只是一次。
- Get rid of
broadcast
channel - Somehow pass & get from request to which client your user want to connect. Some room number/name, secret code? For example an URL parameter
/ws?chat=abc
. You probably would need to maintain amap[chatid][]*websocket.Conn
- Match 2 (or more) clients.
- Maintain a map, probably of type
map[*websocket.Conn]*websocket.Conn
- On receiving a message from a client lookup the map and send the message to the matching client. In similar way as in
handleMessages()
but just once.
请注意StackOverflow不是要求为您编写代码的地方。
这篇关于Golang一对一聊天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文