C#发送了相同的Socket多个对象 [英] C# Sending multiple objects over same Socket

查看:365
本文介绍了C#发送了相同的Socket多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图发送多个不同的对象(当然,它们是同一个对象类型,只是不同的值)从一个插座到另一个。我蛮好用下面的代码发送一个对象:

I'm trying to send multiple different objects (well, they are the same object types, just with different values) from one socket to another. I can send one object just fine using the following code:

客户:

var buffer = new byte[1024];
var binFormatter = new BinaryFormatter();
using (var ms = new MemoryStream())
{
    int bytesRead;
    while ((bytesRead = _clientReceive.Receive(buffer)) > 0);
    {
        ms.Write(buffer, 0, bytesRead);
    } 

    ms.Position = 0;
    message = (Message)binFormatter.Deserialize(ms);
} 



服务器:

server:

var gm = new Message { Message = "ObjectType", Object = Data };

using (var mem = new MemoryStream())
{
    var binFormatter = new BinaryFormatter();
    binFormatter.Serialize(mem, gm);
    var gmData = mem.ToArray();
    client.Send(gmData, gmData.Length, SocketFlags.None);
    client.Close();
}



但是如果我想发送多个消息(把完整的客户端代码中循环,不叫 client.Close())我将如何能够确定时,完整的对象已由客户接收?把客户端代码在一个循环是这样的:

but if I want to send multiple messages (put the full client code in a loop and not call client.Close()) how would I be able to determine when the full object has been received by the client? Putting the client code in a loop like this:

while (_isReceivingStarted)
{
    var buffer = new byte[1024];
    var binFormatter = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        int bytesRead;
        while ((bytesRead = _clientReceive.Receive(buffer)) > 0)
        {
            ms.Write(buffer, 0, bytesRead);
        }
        ms.Position = 0;
        message = (Message) binFormatter.Deserialize(ms);
    }
    // Do stuff then wait for new message
}

客户端将在 _clientReceive.Receive(缓冲)挂起,因为它没有收到关闭()从客户端和从来没有得到0接收的字节。如果我关闭该服务器上的连接,它会遍历,然后在反序列化的MemoryStream错误而不是在另一个对象的预期在 _clientReceive.Receive(缓冲)阻塞出被发送。

the client will hang at _clientReceive.Receive(buffer) because it doesn't receive the Close() from the client and never get the 0 received bytes. If I close the connection on the server, it will loop through and then error out at the Deserialize MemoryStream instead of blocking at the_clientReceive.Receive(buffer) in anticipation of another object being sent.

我希望这是有道理的。任何指针?

I hope this makes sense. Any pointers?

推荐答案

您可能会发送通知接收端多少字节期望的头信息。这类似于在HTTP内容长度指令。另一种选择,让你在最后发送自定义字符串终止(显然它不能出现在序列化对象的二进制负载,这是任何地方的点点滴滴,为什么前者的解决方案是什么,我会做)。

You might send a header message that informs the receiving end how many bytes to expect. This is similar to the Content-Length directive in HTTP. Other option, make a custom termination string you send at the end (obviously it can't appear bit for bit anywhere in the serialized objects' binary payload, which is why the former solution is what I'd do).

这篇关于C#发送了相同的Socket多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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