sending/receiving objects through tcpclient
I have to send/recieve objects (of a custom class made by me) in my C# .NET 4.0 application and I would like a good tutorial to get me started because I've searched on Google and there seem to be a lot of problems with serialization/deserialization and although the problems we开发者_如何学编程re solved, there are a lot of ugly hacks.
Regards, Alexandru Badescu
I've made a transport that does just this:
http://fadd.codeplex.com/SourceControl/changeset/view/58859#1054822
The library is work in progress, but the BinaryTransport works. It will also attempt to reconnect if it get disconnected.
Example:
public class Example
{
private BinaryTransport<Packet> _client;
private ServerExample _server;
public void Run()
{
// start server
_server = new ServerExample();
_server.Start(new IPEndPoint(IPAddress.Loopback, 1234));
// start client
_client = new BinaryTransport<Packet>(new IPEndPoint(IPAddress.Loopback, 1234));
// send stuff from client to server
_client.Send("Hello world!");
// send custom object
_client.Send(new User { FirstName = "Jonas", LastName = "Gauffin" });
}
}
public class ServerExample
{
private readonly List<BinaryTransport<Packet>> _clients = new List<BinaryTransport<Packet>>();
private SimpleServer _server;
private void OnClientAccepted(Socket socket)
{
var client = new BinaryTransport<Packet>(socket);
client.Disconnected += OnDisconnected;
client.ObjectReceived += OnObject;
_clients.Add(client);
}
private void OnDisconnected(object sender, EventArgs e)
{
var transport = (BinaryTransport<Packet>) sender;
transport.Disconnected -= OnDisconnected;
transport.ObjectReceived -= OnObject;
}
private void OnObject(object sender, ObjectEventArgs<Packet> e)
{
Console.WriteLine("We received: " + e.Object.Value);
}
public void Start(IPEndPoint listenAddress)
{
_server = new SimpleServer(listenAddress, OnClientAccepted);
_server.Start(5);
}
}
[Serializable]
public class Packet
{
public object Value { get; set; }
}
[Serializable]
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Update
I've made a new framework: http://blog.gauffin.org/2012/05/griffin-networking-a-somewhat-performant-networking-library-for-net/
If you have control over the objects you could decorate them with the [Serializable]
attribute and use BinaryFormatter for serialization/deserialization.
For TCP/IP communication I highly recommend Stephen Cleary's FAQ, you should pay special attention to Message Framing. You might also want to take a look at his NitoSockets implementation.
All that assuming you can't just use WCF, of course.
精彩评论