gpt4 book ai didi

go - 当多个客户端使用它时,Gorilla Websocket非常慢

转载 作者:行者123 更新时间:2023-12-01 22:23:41 33 4
gpt4 key购买 nike

我使用gorilla websocket制作了一个小型聊天应用程序。当只有一个客户端时,它的速度很快。但是,当我与另一个客户端连接时,即使托管在本地计算机上,聊天也可能需要3秒钟才能更新。

Websocket的代码:

var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan Message)
var upgrader = websocket.Upgrader{}
func main() {
router.HandleFunc("/ws", handleConnections)
err := http.ListenAndServe(":80", router)
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
defer ws.Close()
clients[ws] = true
for {
var msg Message
err := ws.ReadJSON(&msg)
if err != nil {
log.Printf("error: %v", err)
delete(clients, ws)
break
}
broadcast <- msg
}
}

func handleMessages() {
for {
msg := <-broadcast
log.Println(msg)
database, _ := sql.Open("sqlite3", "./database.db")
statement, _ := database.Prepare("CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, username TEXT, message TEXT, timestamp INTEGER)")
statement.Exec()
statement, _ = database.Prepare("INSERT INTO messages (username, message, timestamp) VALUES (?, ?, ?)")
statement.Exec(&msg.Username, &msg.Message, &msg.Timestamp)
for client := range clients {
err := client.WriteJSON(msg)
if err != nil {
log.Printf("error: %v", err)
client.Close()
delete(clients, client)
}
}
}
}

完整代码: https://github.com/mismaah-abdulla/Chatapp-Backend/blob/de8cc0eb88fa7f18b293bb0f2229368887c53adf/src/main.go

最佳答案

问题是尝试写入时数据库已锁定。解决方法很简单
每次运行查询时都将row.Close()推迟。
例如:

func messages(w http.ResponseWriter, r *http.Request) {
rows, _ := database.Query("SELECT username, message, timestamp FROM messages")
defer rows.Close()
var messages []Message
for rows.Next() {
var msg Message
rows.Scan(&msg.Username, &msg.Message, &msg.Timestamp)
messages = append(messages, msg)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(messages)
}

关于go - 当多个客户端使用它时,Gorilla Websocket非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61308613/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com