在TcpClient的序列化的数据需要状态量? [英] Serialized data on tcpclient needs to state amount?

查看:159
本文介绍了在TcpClient的序列化的数据需要状态量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经发送数据如使用TcpClient的字节,我想送我自己的类,而不是字节的数据。

I have sent data as byte using TcpClient and I wanted to send my own class instead bytes of data.

通过数据的字节,我的意思是,我送转换成字节这样的数据:

By bytes of data, what I meant is that I am sending the data converted into bytes like this:

using (MemoryStream bufferStream = new MemoryStream())
{
    using (BinaryWriter bufferData = new BinaryWriter(bufferStream))
    {
        // Simple PONG Action
        bufferData.Write((byte)10);
    }

    _logger.Info("Received PING request, Sending PONG");
    return bufferStream.ToArray();
}

和,而不是我想就这样送,无需声明其大小或W / E

And instead I would like to send it like this, without having to declare its size or w/e

public class MyCommunicationData
{
    public ActionType Action { get; set; }
    public Profile User { get; set; }
    ...
}

通常情况下,当我把我的数据字节的前5个字节我用的指示行动,邮件大小。

Normally, when I send my data as bytes the first 5 bytes I use to indicate the action and the message size.

但是,如果我迁移到序列中的所有数据作为一个单独的类,我还需要送什么行动,它的大小是或者使用序列化的消息在客户端和服务器会知道读什么书等等,还是有办法做到这样我就可以,而不必指定的事情了序列化对象发送它?

But if I migrate to serialize all the data as a single class, do I still need to send what action and size it is or using serialized messages the client and server would know what to read etc or is there a way to do so I can send it without having to specify things out of the serialization object ?

不知道这是否在这里,重要的我使用的AsyncCallback 来读取和写入到网络流:

Not sure if this matters here, I am using AsyncCallback to read and write to the network stream:

_networkStream = _client.tcpClient.GetStream();
_callbackRead = new AsyncCallback(_OnReadComplete);
_callbackWrite = new AsyncCallback(_OnWriteComplete);

让我知道,如果你需要我张贴任何其他功能。

Let me know if you need me to post any other functions.

推荐答案

如果您使用的是基于文本的序列化(为前,JSON),你可以利用的StreamReader的的ReadLine 和的StreamWriter的的WriteLine (从tcpClient.GetStream创建)。

If you use a text based serializer(for ex, Json), you can utilize StreamReader's ReadLine and StreamWriter's WriteLine (created from tcpClient.GetStream).

您code会是这样

 writer.WriteLine(JsonConvert.SerializeObject(commData))

和获得对另一端的数据

var myobj = JsonConvert.DeserializeObject<MyCommunicationData>(reader.ReadLine())

- 编辑 -

--EDIT--

//**Server**
Task.Factory.StartNew(() =>
{
    var reader = new StreamReader(tcpClient.GetStream());
    var writer = new StreamReader(tcpClient.GetStream());
    while (true)
    {
        var myobj = JsonConvert.DeserializeObject<MyCommunicationData>(reader.ReadLine());
        //do work with obj 
        //write response to client
        writer.WriteLine(JsonConvert.SerializeObject(commData));
    }
}, 
TaskCreationOptions.LongRunning);

这篇关于在TcpClient的序列化的数据需要状态量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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