Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

c# - Serialized data on tcpclient needs to state amount?

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

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

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 ?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Your code would be something like

 writer.WriteLine(JsonConvert.SerializeObject(commData))

and to get the data on the other end

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...