go-socket.io icon indicating copy to clipboard operation
go-socket.io copied to clipboard

How do I find an instance of socketio.Conn corresponding to s.id ()

Open liewkaitsan opened this issue 3 years ago • 4 comments

I am trying to send a message to the specified s.ID () ,but I cannot find the corresponding socketio.Conn via s.Id ().

liewkaitsan avatar Mar 10 '21 03:03 liewkaitsan

A bit more of an example code would help to solve your problem. Please don't share sensitive content.

p000ic avatar Mar 14 '21 14:03 p000ic

@p000ic

A bit more of an example code would help to solve your problem. Please don't share sensitive content.

I looked at the example in the readme.md, where the conn.Emit() is used in the callback function that the server receives when the client sends data.So you've got the current conn, However, in my current scenario, the server needs to receive the SID from another system interface and find the corresponding conn according to the SID.Then send the message via conn.Emit()]

liewkaitsan avatar Mar 15 '21 06:03 liewkaitsan

system

@p000ic

A bit more of an example code would help to solve your problem. Please don't share sensitive content.

I looked at the example in the readme.md, where the conn.Emit() is used in the callback function that the server receives when the client sends data.So you've got the current conn, However, in my current scenario, the server needs to receive the SID from another system interface and find the corresponding conn according to the SID.Then send the message via conn.Emit()]

U can store the ID->conn mapping data by yourself when the conn connecting,it's easy way

ralfbawg avatar May 12 '21 08:05 ralfbawg

var SocketConMap = make(map[string]socketio.Conn)

server.OnConnect("/", func(s socketio.Conn) error {
    s.SetContext("")
    userID := getCookieByName("userID", getCookies(s.RemoteHeader().Get("Cookie")))
    fmt.Println("connected:", s.ID(), userID)
    SocketConMap[userID] = s
    return nil
})

if v, ok := util.SocketConMap[uid]; ok {
    time := time.Now().Format("15:04:05.000")
    v.Emit("msg", util.SocketData{Time: time, Msg: "服务端发送消息到指定客户端"})
}

yuedun avatar May 25 '21 02:05 yuedun