C#的TcpClient:发送使用分离器序列化对象? [英] C# TcpClient: Send serialized objects using separators?

查看:128
本文介绍了C#的TcpClient:发送使用分离器序列化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据序列化(这里所说的 http://stackoverflow.com/a/7849374/985798 )我想重新设计我的小TCP应用程序,这是使用字符串消息到现在。

Based on serialization (mentioned here http://stackoverflow.com/a/7849374/985798) I am trying to reengineer my small tcp application, which was using a string message until now.

不过,我遇到了一个小问题,我想知道有什么解决方案,您会推荐我使用:

But I ran into a small problem and I would like to know what solution you'd recommend me to use:

如果我想在一个非常小的时间间隔发送多条消息,他们将在排队合并,客户端将在同一时间收到两个消息,这将结束与一个破碎的对象。在过去,我解决了这个问题,用字符串分隔符|结束|我能够分裂,并在foreach循环处理。

If I am trying to send more than one message in a very small interval, they will be merged in the "queue" and the client will receive both messages at the same time, which will end up with a single broken object. In the past I solved this problem with a string separator "|end|" and I was able to split it and process it in a foreach loop.

这是一个好办法?你将如何解决基于序列化对象的字节数组这个问题?你会使用字节[] 分隔符或使用其他解决方案?

Is that a good approach? How would you solve that problem based on serialized object byte arrays? Would you use a byte[] delimiter or use another solution?

推荐答案

下面是一个通用的例子来发送邮件使用Json.Net客户端和服务器之间的对象。它使用换行符字符作为分隔符。因此,所有你需要的是从网络流创建的StreamReader和StreamWriter和使用的ReadLine和WriteLine方法....

Here is a generic example to send objects between client and server using Json.Net. It uses NewLine char as separator. So All you need is to create StreamReader and StreamWriter from network streams and to use ReadLine and WriteLine methods....

(PS:由于Json.Net逃脱换行字符序列中包含的信息不会引起问题...)

(PS: Since Json.Net escapes NewLine char in serialization, messages containing it doesn't cause problems...)

void SendObject<T>(StreamWriter s, T o)
{
    s.WriteLine( JsonConvert.SerializeObject(o) );
    s.Flush();
}

T ReadObject<T>(StreamReader r)
{
    var line = r.ReadLine();
    if (line == null) return default(T);
    return JsonConvert.DeserializeObject<T>(line);
}


SemaphoreSlim serverReady = new SemaphoreSlim(0);
//SERVER
Task.Factory.StartNew(() =>
    {
        TcpListener listener = new TcpListener(IPAddress.Any, 8088);
        listener.Start();
        serverReady.Release();
        while(true)
        {
            var client = listener.AcceptTcpClient();
            Task.Factory.StartNew(() =>
                {
                    Console.WriteLine("Client connected...");
                    var reader = new StreamReader(client.GetStream());
                    var obj = ReadObject<string>( reader) ;
                    while(obj != null)
                    {
                        Console.WriteLine("[" + obj + "]");
                        obj = ReadObject<string>(reader);
                    }
                    Console.WriteLine("Client disconnected...");
                });
        }

    });


serverReady.Wait();
//CLIENT
Task.Factory.StartNew(() =>
{
    TcpClient client = new TcpClient();
    client.Connect("localhost", 8088);
    var writer = new StreamWriter(client.GetStream());
    for (int i = 0; i < 10; i++)
    {
        SendObject(writer, "test\nmessage" + i); //message containing `\n` :)
    }
    client.Close();
});

这篇关于C#的TcpClient:发送使用分离器序列化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆