Socket chat on go

Good afternoon.

Trying to figure out sockets on go.

How do I identify a specific connection?

For example, one user gives the server such a request:

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

The server must respond to {status:true} and go through all the connected users, find the user id 222 there, and send this message to him specifically.

Using the example hence. With packages from here. But here is a general chat. It is necessary to filter somehow, from who and to whom to forward the data. How do I do this?

Thanks.

Author: Виталина, 2015-03-21

2 answers

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

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

Well, pass the messages accordingly, something like this:

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

P.S. Specifically the package github.com/gorilla/websocket I did not use it, how it works there, I do not know, I use code.google.com/p/go.net/websocket, so the code is purely to outline the idea more clearly. :)

 3
Author: Павел Вершинин, 2015-03-22 12:19:56

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

  1. Make a common message store - 'from', 'to', 'text', 'new / read' - and let each client climb into it with a certain periodicity and take everything 'new'.

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

Something like that.

 2
Author: Борис, 2015-03-22 12:18:42