Sergej Popov
Sergej Popov

Reputation: 3021

Fleck WebSockets

I want to use Fleck for my WebSocket project, Server side looks pretty straightforward, but how to I differentiate opened connections. is there some sort of ID? The only way I can think of is to create GUID in OnOpen event and pass it back to client. is there a smarter solution?

Basic server set up:

socket.OnOpen = () =>
{
    Console.WriteLine("Open!"); 
    allSockets.Add(socket);
};

socket.OnClose = () =>
{
    Console.WriteLine("Close!");
    allSockets.Remove(socket);
};

socket.OnMessage = message =>
{
    Console.WriteLine(message);
    allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
};

E.G. how would I make a chat room so all connection receive message except for the one sending.

Fleck server here: https://github.com/statianzo/Fleck

Upvotes: 4

Views: 13780

Answers (4)

statenjason
statenjason

Reputation: 5180

Fleck now creates a Guid Id on the WebSocketConnectionInfo for every connected client. This will help in cases where multiple connections are using the same IP. See the related commit here:

https://github.com/statianzo/Fleck/commit/fc037f49362bb41a2bc753a5ff51cc9da40ad824

Upvotes: 6

Neil Mosafi
Neil Mosafi

Reputation: 460

It's a different socket instance per client, so I would have thought you should be able to do:

allSockets.Where(x => x != socket).ToList().ForEach(s => s.Send("Echo: " + message));

Upvotes: 0

Sphvn
Sphvn

Reputation: 5343

I started something similar to what you are asking I am doing. In my case I am using the ConnectionInfo.Path to differ between what my sockets are doing.

You can gain a lot of information already out of the ConnectionInfo

socket.ConnectionInfo.{Host|Path|Origin|SubProtocol|ClientIPAddress|Cookies}

So to answer your question to give it to everyone but the sender you can differentiate each socket based on the ConnectionInfo (if applicable you could create a UID out of this info also)


As a very basic example:

If you know each Client will have a different IP something like the following would work:

 socket.OnMessage = message =>
 {
     foreach (IWebSocketConnection socketConnection in allSockets.Where(socketConnection => socket.ConnectionInfo.ClientIpAddress != socketConnection.ConnectionInfo.ClientIpAddress))
     {
         socketConnection.Send("Echo: " + message);
     }
 };

Upvotes: 1

Ben Felda
Ben Felda

Reputation: 1484

Ask the user for a user name, and attach the username to the the socket address:

var wsimpl = window.WebSocket || window.mozWebSocket;
window.ws = new wsimpl('http://localhost:8080/myApp_' + userName, myProtocol);

then strip out the userName on the service side after the socket has been opened with socket.WebSocketConnectionInfo.path. There is also a clientip property that can be used also. I am doing this and it works great.

Upvotes: 2

Related Questions