Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...