通过tcpclient发送/接收对象

时间:2010-10-31 13:49:31

标签: c# serialization tcpclient

我必须在我的C#.NET 4.0应用程序中发送/接收对象(由我制作的自定义类),我想要一个很好的教程让我开始,因为我在Google上搜索过,似乎有一个序列化/反序列化存在很多问题,虽然问题已经解决,但还有很多难看的黑客攻击。

此致 Alexandru Badescu

3 个答案:

答案 0 :(得分:2)

我做了一个运输就是这样:

http://fadd.codeplex.com/SourceControl/changeset/view/58859#1054822

图书馆正在进行中,但BinaryTransport正常运作。如果它断开连接,它也会尝试重新连接。

示例:

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; }
}

<强>更新

我制作了一个新框架:http://blog.gauffin.org/2012/05/griffin-networking-a-somewhat-performant-networking-library-for-net/

答案 1 :(得分:1)

如果您可以控制对象,可以使用[Serializable]属性修饰它们,并使用BinaryFormatter进行序列化/反序列化。

答案 2 :(得分:1)

对于TCP / IP通信,我强烈推荐Stephen Cleary's FAQ,您应该特别注意Message Framing。您可能还想查看他的NitoSockets实现。

当然,假设你不能只使用WCF。