gpt4 book ai didi

go - 从列表中删除客户端会终止其他连接

转载 作者:数据小太阳 更新时间:2023-10-29 03:29:22 26 4
gpt4 key购买 nike

为什么要杀死一个简单的“ClientList.Remove(entry)”所有来自其他客户端的连接?

我有一个非常简单的 Go TCP 服务器,可以进行连接处理和登录处理。之后,如果创建一个客户端并使用 TCP 客户端启动一个 GO Routine。

newClient := &Client{"", "", login.LoginToken, conn}去 ClientReader(newClient)ClientList.PushBack(*newClient)

Go 例程读取所有传入数据。当连接超时或网络发生变化时(客户端获得新 IP)它将客户从客户列表中删除。

但是当它从列表中删除客户端时......所有其他客户端连接都死了?在循环中它找到正确的客户端并将其删除。

看看removeloop:

常规:

func ClientReader(client *Client) {
buffer := make([]byte, 2048)
for {
bytesRead, error := client.Conn.Read(buffer)
if error != nil {
Log(error)
break
}

var m Message
err := json.Unmarshal([]byte(buffer[0:bytesRead]), &m)
if err != nil {
Log(err)
} else {

switch m.Cmd {
case "Message":

case "Ping":
Log("Ping from: ", client.Name, " on ", client.Conn.RemoteAddr())
client.Conn.SetDeadline(time.Now().Add(25 * time.Second))
pong := []byte(`{"PONG":"..."}` + "\r\n")
client.Conn.Write(pong)
Log("PONG: " + time.Now().Format(time.RFC850))
Log("User Online: " + strconv.Itoa(ClientList.Len()))
Log("Goroutines: " + strconv.Itoa(runtime.NumGoroutine()))

default:
Log("Not supported Command: ", m.Cmd)
clienterror := []byte(`{"Err":"Command not supported"}` + "\r\n")
client.Conn.Write(clienterror)
}
for i := 0; i < 2048; i++ {
buffer[i] = 0x00
}
}

}

RemoveLoop:
for entry := ClientList.Front(); entry != nil; entry = entry.Next() {
listclient := entry.Value.(Client)
if client.Conn.RemoteAddr() == listclient.Conn.RemoteAddr() {
ClientList.Remove(entry)
Log("## SEARCH: ", client.Name, client.Conn.RemoteAddr())
Log("## FOUND: ", listclient.Name,listclient.Conn.RemoteAddr())
Log("## REMOVED: ", entry.Value)
break RemoveLoop
}
}
Log("Exit Client Reader Routine ", client.Name, " on ", client.Conn.RemoteAddr())

}

最佳答案

感谢您的快速回答:)我已经提出了您的建议(线程安全的 clientList),但我的问题仍然存在。

在测试和一些重写之后,我在服务器日志中看到了一件非常疯狂的事情。

在 ServerStart 之后它有 4 个 Goroutines .... 没问题。 (Golang 实习生例程?)

客户端 1 登录...并且 Goroutine 5 已启动...正常(第一个 ClientReader)客户端 2 登录...并且 Goroutine 6 已启动...正常(第二个 ClientReader)

客户端 2 是一部手机,我在手机和 WLAN 之间随机切换。

服务器检测到来自电话的 ip 更改...没问题。手机使用新的 IP 地址登录,并且服务器在 ConnectionTimout 后终止旧的连接......是好的。

在从手机发出 2-n 次 ping 后,服务器将 Goroutines 从 6 个增加到 7 个,手机失去了连接?

Goroutine 不是 Clientreader(它记录每个 START 和 EXIT)Clientreader 是我代码中唯一的 Goroutine。

GOLANG 在做什么,为什么会有一个 7 号协程?

关于go - 从列表中删除客户端会终止其他连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198611/

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