C# Async object transmission (Sockets?)
I am trying to figure out what the best way to approach Async object transmission.
What I want to do is have multiple instances of the same application open across a network connection (5-10 clients) that connect to one server, and when one of the applications updates its data, I need to transmit that update to all the other instances.
The update objects will be similar to this:
public class UpdateData
{
public double Angle { get; set; }
public double Azimuth { get; set; }
public Point Position { get; set; }
public Guid ObjectGuid { get; set; }
}
The data won't be very big, but objects of this type will be transmitted about 10-50 times per second from each client to all the other clients.
What is the best way to handle this kind of data transmission?
What I was thinking is have a server object listen and accept connections using something similar to this:
private void BtConnectClick(object sender, EventArgs e)
{
int port;
if开发者_StackOverflow中文版 (!int.TryParse(tbPort.Text, out port))
{
MessageBox.Show("Please enter a valid port into the textbox");
tbPort.Text = "";
return;
}
try
{
_listener = new TcpListener(IPAddress.Any, port);
_listener.Start();
_listener.BeginAcceptSocket(OnClientConnect, _listener);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
var s = _listener.EndAcceptSocket(asyn);
_clients.Add(s); // List<Socket> object
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
But how should the server handle the data transmission?
I know I should be trying to receive data from all of the sockets in _clients
and once I receive data, I need to forward it onto all the other sockets in _clinets
, but how should I do this? How and where should I detect when a client has terminated its connection?
Also, the clients should be listening for data to be received from the server as well as sending data to the server. Can I handle all of that with one socket or should I use 2?
Thanks for any help!
Personally, I would leave this to a message-bus/service-bus, or anything else with pub/sub. My preference would be redis: http://redis.io/commands#pubsub
Re the object, I would use protobuf-net, simply because I know it will produce tiny binary for the above message. Sending (PUBLISH) a BLOB to a named redis channel will cause it to be distributed to all listeners on that channel.
精彩评论