Good day.

Trying to deal with sockets on go.

How to identify a specific connection?

For example, one user gives the server the following request:

{action:message,from_id:111,to_id:222,message:'Привет. Как дела?'} 

The server should reply {status:true} and go through all the connected users, find the user id 222 and send this particular message to him.

I use an example from here . With packages from here . But here is a general chat. It is necessary to somehow filter from whom and to whom to send data. How to do it?

Thank.

    2 answers 2

    Store client connections in the map, where, as the key of the user ID, something like this:

     var connections = make(map[int]*websocket.Connection, 0) 

    Well, send messages accordingly, something like this:

     if connections[userId] != nil { connections[userId].Send() } 

    PS Specifically, the package github.com/gorilla/websocke t I didn’t use it , how it works there , I don’t know, I’m using code.google.com/p/go.net/websocket , so the code is only to make the idea clearer. :)

    I am a small specialist in Go, so I can advise conceptually:

    1. Make a common repository of messages - 'from', 'to whom,' 'text', 'new / read' - and let every client climb into it with a certain periodicity and take all the 'new'.

    2. Consider the option with 'named channels' - when a new chat client is connected, a name channel is created for it, the channel list is stored in some hash, where the key is the client ID. All messages to this client to send through the appropriate channel.

    Something like this.

    • @ Roman Rakzin - I didn’t work with golang, but once I did this with C ++, I had to create an array and identify all the connected users: id: 111 is a socket [0], id: 222 is a socket [1], etc. . In general, deal with the basic principles of golang sockets - and you will succeed! - wh1te
    • That principle I thought so, but how to do it?))) - Rakzin Roman