Handler for pong message in WampSharp client - c#

I have a WampSharp client which successfully pings my Wamp WS server created in python every 1 minute.
I am sending a pong message from the server to the client on the receipt of the ping.
I would like to know whether there is any handler which will handle the receipt of the pong message in WampSharp client so that I could perform certain tasks at client side?
And if there isn't any separate handler for the pong message then is there any handler to handle the data received from the server like in traditional WebSocket client which is as follows?
webSocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(webSocket_MessageReceived);
Thanks in advance.

I just uploaded to NuGet a version of WampSharp that allows you to specify the underlying WebSocket you want to use for a WampChannel.
Usage:
DefaultWampChannelFactory factory = new DefaultWampChannelFactory();
WebSocket socket = new WebSocket("ws://localhost:9090/ws", "wamp");
IWampChannel<JToken> channel = factory.CreateChannel(socket);
socket.DataReceived += OnDataReceived;
await channel.OpenAsync();
As you see, you can also subscribe to underlying WebSocket's events. I don't really like this, since this removes WampSharp's WebSocket encapsulation, but if you know what you're doing, I won't stop you.

Related

Why does my basic tcp chat application only work when connections are ended via ECONNRESET in nodejs?

I have a weird scenario and I'm not sure how to solve it.
I have a simple tcp chat server in nodejs and my clients are currently in native C#, and eventually will move to Unity. I have my own networking library which creates the TCP connection and handles messages etc, and works fine in some cases until it comes to disconnecting.
The server is running on an EC2 instance and I am loading two windows on my PC to test the multiple connections. When I close the window, I receive this error in the nodejs server console
Error: read ECONNRESET
at exports._errnoException (util.js:870:11)
at TCP.onread (net.js:544:26)
Which is fine, because this is the scenario where it works. I'm guessing this just means that the connection was abruptly closed (closing the window).
However problems arise when I instruct the socket to be shutdown.
I am porting my client to Unity and when closing the client, it does not produce this ECONNRESET error and the connection never closes abruptly (like I'd expect it to), so in this case I have to manually close the connection on the client which results in a different error.
Error: This socket has been ended by the other party
at Socket.writeAfterFIN [as write] (net.js:268:12)
at /opt/chat/chat.js:32:10
at Array.forEach (native)
at broadcast (/opt/chat/chat.js:31:10)
at Socket.<anonymous> (/opt/chat/chat.js:26:2)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at nextTickCallbackWith2Args (node.js:441:9)
at process._tickCallback (node.js:355:17)
When I receive this error on the server, the other connected clients can continue messaging the server, however they cannot receive messages from it.
My nodejs server was pulled from github here:
https://gist.github.com/creationix/707146
// Load the TCP Library
net = require('net');
// Keep track of the chat clients
var clients = [];
// Start a TCP Server
net.createServer(function (socket) {
// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort
// Put this new client in the list
clients.push(socket);
// Send a nice welcome message and announce
socket.write("Welcome " + socket.name + "\n");
broadcast(socket.name + " joined the chat\n", socket);
// Handle incoming messages from clients.
socket.on('data', function (data) {
broadcast(socket.name + "> " + data, socket);
});
// Remove the client from the list when it leaves
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " left the chat.\n");
});
// Send a message to all clients
function broadcast(message, sender) {
clients.forEach(function (client) {
// Don't want to send it to sender
if (client === sender) return;
client.write(message);
});
// Log it to the server output too
process.stdout.write(message)
}
}).listen(5000);
// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 5000\n");
Scenario
Let's assume we have CLIENT A on the left and CLIENT B on the right
On initial connection, they can both chat fine.
CLIENT B wishes to disconnect, and the code forces the disconnect by terminating the socket. The nodejs server receives the error "This socket has been ended by the other party" and broadcasts that this player has disconnected to CLIENT A
CLIENT A wishes to continue communicating, regardless that no one is connected. CLIENT A continues typing and sending messages, however the messages are not being received once CLIENT B has disconnected. However, the messages are indeed being sent to the server.
CLIENT A is NOT receiving his own messages.
CLIENT B wishes to reconnect to continue chatting and does so.
CLIENT A sends message 'hello'
CLIENT B sends message 'hello'
CLIENT B is seeing both messages, and experiencing a normal chat, however CLIENT A is not seeing any of the messages and is stuck on a blocking call trying to read data.
This is ONLY when I force the socket closed, and it works perfectly fine when I receive the ECONNRESET error. How can I replicate this error, or fix my issue?
EDIT
I have managed to reproduce the ECONNRESET error and now it works, but it still doesn't explain why it doesn't work with other errors.
The methods Close and GetStream().Close in C# TcpClient are not sufficient it seems to close a connection properly. Instead I had to access the socket directly and close that.
Closing the socket directly works in a native C# application but not in Unity.
To replicate this error in Unity I have to use
Shutdown(SocketShutdown.Receive);

Connection specific AppendShutdownHandler

I'm using NetworkComms.Net and I'm currently trying to create a sort of forwarder which listens on a port (calling it GATEWAY), which receive a certain packet (from CLIENT) which will tell him where to redirect next pacekts coming from the same client.
Example:
CLIENT tell GATEWAY that he needs to get to SERVER:serverport
GATEWAY creates a connection to SERVER:serverport
CLIENT sends packets to GATEWAY which sends them to SERVER
SERVER sends back a response, which goes through the GATEWAY to the CLIENT.
I had it working with Net.Sockets and I’m now changing to NetworkComms.
The problem I’m facing is that when a connection from Gateway (client) to Server (listening server) is closed, the Gateway trigger the global callbacks for connection/disconnection:
NetworkComms.AppendGlobalConnectionCloseHandler(ClientDisconnected);
NetworkComms.AppendGlobalConnectionEstablishHandler(ClientConnected);
Those callbacks are supposed to be only called when a client connect or disconnect on the Gateway
This is the code i’m currently using to start the listener.
NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions<ProtobufSerializer, , LZMACompressor>();
NetworkComms.DefaultSendReceiveOptions.IncludePacketConstructionTime = NetworkComms.DefaultSendReceiveOptions.ReceiveHandlePriority = QueueItemPriority.AboveNormal;
NetworkComms.AppendGlobalConnectionCloseHandler(SessionClosed);
NetworkComms.AppendGlobalConnectionEstablishHandler(NewSessionConnected);
NetworkComms.AppendGlobalIncomingPacketHandler<string>("ECHO", SocketCommands.HandleIncomingECHOPacket);
Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 10000));
I suppose this is like a “global” way of starting It?
How do I start one then add those Connected/Disconnected handlers to just the listener?
Thanks

WCF Net.TCP: Most efficient way to broadcast messages to a lot of clients

I have a WCF service hosted with Net.TCP binding to which a lot of clients (> 100) may connect and receive various broadcast messages. The same message is sent to all clients and the current way I'm currently doing it is to have dedicated thread which waits on a BlockingCollection for new messages and as soon as new message arrives it iterates over the list of client callback connections and calls a method which receives the message as an argument.
So my code currently looks like this:
var msg = ... get message from queue ...
foreach(var client in clients)
client.SendMessage(message)
This design has following problems:
Clients can not receive new message until I'm finished sending a message to all clients
I would like to detect slow clients and possibly disconnect them
The message is being serialized as many times as I have clients (I could change it so that I serialize the message before sending it but I would need to change the signatore of SendMessage to SendMessage(byte[] content) and this is not something I would like to do)
Does anybody has experience with such problems? Any tips/tricks/hints?
It seems you have to use multicasts instead of dedicated communication. So each new client will need to join the cast channel (see IGMP for details) and then your server will fire-and-forget once per message you need to publish.

Error handling during broadcasting message using WebSocketCollection object

I'm currently using .Net 4.5 websocket package to support websocket service on windows 2012 server.
Using WebSocketCollection object I'm succesfully able to broadcast message to all the clients.
private static WebSocketCollection m_clients = new WebSocketCollection ();
m_clients.Broadcast(“Hello all”));
Here how to be sure all clients have received broadcasted messages? If some clients couldn't able to receive message how can I track those error messages? What king of error handling mechanism shall I need to use?
There is a onError virtual function. But I'm not sure how it will work during failure case of broadcasted message.
public virtual void OnError();
Could you not get the clients to "Acknowledge" the receipt of a packet, if a client does not Acknowledge the packet then chances are it wasn't received correctly.
If you are just wanting to keep the connection alive send a "Ping" message to the client before timeout. Likewise you could code the client to Ping the server at a scheduled time, if no Ping received then that could indicate that there is a problem?

How to react after receiving a packet in TCP server

I am new in C#. I made a very simple TCP server and TCP Client. I am able to send some message from client to server. If I want see the message which came from client on server I am using button which view the message. Now my stupid question. How make a function which will react on new comming packet from client to view it imediately in textBox? Simple what I want>>> IF comes a new packet......DO SOMETHING.
Generally, a TCP server does this:
Create a thread to listen for connection requests
Do a TcpListener.AcceptTcpClient in the above thread
When AcceptTcpClient accepts a connection, create a new thread
In new thread, do a GetStream and then Read the stream.
When data arrives, decode it and send a message to the GUI / Controller / whatever.
Process the TCP message and send a response message to the TCP thread to Write on the stream the result of the processing.

Categories