如何通过套接字发送对象 C#

发布于 2024-12-13 18:42:02 字数 1763 浏览 0 评论 0原文

我有一个对象列表,我想通过 TCP 套接字连接发送它。一种方法是获取对象列表并获取用逗号分隔它们的所有值和接收数据,并在另一端获取对象中的值。我可以发送对象列表吗,因为它可以在 WCF Web 服务中完成。那么你能告诉我怎么做吗?谢谢!

我确实已经为此创建了一个 WCF 服务,但对其进行了更改,因为它有一些无法解决的问题。所以我正在创建这个客户端服务器应用程序。

此外,正在发送的数据每隔几秒就会刷新一次,并且很多用户都需要它。经过一番研究,我发现这将是一个更好的选择。

我有这个类,我通过它发送消息

public void SendMessage(string text)
{
    Byte[] bytesSent = Encoding.UTF8.GetBytes(text);
    SocketAsyncEventArgs writeEventArgs = new SocketAsyncEventArgs();
    writeEventArgs.SetBuffer(bytesSent, 0, bytesSent.Length);
    socket.SendAsync(writeEventArgs);
}

,但我宁愿先序列化对象,然后发送它。所以我有一个流并且需要一个字节数组。

这是我必须接收的数据:

void ReceiveData()
{
    try
    {
        int recv;
        string stringData;
        while (true)
        {
            recv = socket.Receive(data);
            stringData = Encoding.ASCII.GetString(data, 0, recv);
            if (stringData == "bye")
                break;
            ClientDataRecievedEventArgs sd = new ClientDataRecievedEventArgs(stringData);
            DataRecieved(this, sd);
        }
        stringData = "bye";
        byte[] message = Encoding.ASCII.GetBytes(stringData);
        socket.Send(message);
        socket.Close();
        this.Dispose();
        return;
    }
    catch (Exception)
    {
        socket.Close();
        this.Dispose();
    }

}

这是我正在使用的:

SoapFormatter formatter = new SoapFormatter();

foreach (Communication.Client Client in server.ClientList)
{
    foreach (ObjectLibrary.Model.PIP p in Repository.GlobalRepository.PIPInformation)
    {

        formatter.Serialize(stream, p);
        Client.SendMessage(stream);
    }
}

如何初始化流? 我需要将数据作为 Stream 获取,以将其反序列化为 Object。

所以我有对象列表我可以序列化整个列表吗?

I have a list of objects and I want to sent it thought TCP socket connection. One way is to take the object list and get all the values separating them by comas and the receiving data and on the other end and values in a object. Can I send a object list as it can be done in WCF web service. It so can you show me how? Thanks!

I did already created a WCF Service for this but changed it as it has a few issues that can't be solved. So I am creating this Client server application.

Also the data that is being send is refreshed every few seconds, and it will be needed by a lot of users. After some research I found out this would be a better option.

I have this class with which I was sending my messages through

public void SendMessage(string text)
{
    Byte[] bytesSent = Encoding.UTF8.GetBytes(text);
    SocketAsyncEventArgs writeEventArgs = new SocketAsyncEventArgs();
    writeEventArgs.SetBuffer(bytesSent, 0, bytesSent.Length);
    socket.SendAsync(writeEventArgs);
}

But I would out rather serialize the object first and then send it. So I have a stream and need as a byte array.

This what I have to receive data:

void ReceiveData()
{
    try
    {
        int recv;
        string stringData;
        while (true)
        {
            recv = socket.Receive(data);
            stringData = Encoding.ASCII.GetString(data, 0, recv);
            if (stringData == "bye")
                break;
            ClientDataRecievedEventArgs sd = new ClientDataRecievedEventArgs(stringData);
            DataRecieved(this, sd);
        }
        stringData = "bye";
        byte[] message = Encoding.ASCII.GetBytes(stringData);
        socket.Send(message);
        socket.Close();
        this.Dispose();
        return;
    }
    catch (Exception)
    {
        socket.Close();
        this.Dispose();
    }

}

This is want I am using:

SoapFormatter formatter = new SoapFormatter();

foreach (Communication.Client Client in server.ClientList)
{
    foreach (ObjectLibrary.Model.PIP p in Repository.GlobalRepository.PIPInformation)
    {

        formatter.Serialize(stream, p);
        Client.SendMessage(stream);
    }
}

How do I initialize the stream?
I need to get the data as Stream to deserialize it to Object.

And so I have list of Objects Can I serialize a whole list?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

英雄似剑 2024-12-20 18:42:02

您必须“序列化”对象,并在另一端反序列化它们。请参阅 http://msdn.microsoft.com/en-us/library/ system.serializedattribute.aspx 了解相关信息。

但您必须小心,如果发送数据时连接发生问题,您可能没有足够的数据来完全重新创建对象,并且您的程序可能会在某些意外的地方失败。仅当您收到所有内容时才创建对象。

You have to "serialize" the objects, and and de-serialize them on the other side. See http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx for information about that.

You have to be careful though, if something happens to the connection while sending the data, you might have not enough data to completely re-create the objects, and your program may fail in some unexpected place. Only create the objects if you received everything.

‘画卷フ 2024-12-20 18:42:02

您有很多用于序列化的对象,例如二进制、XML、JSON,但还有一种远程处理方法,并不是说您可以创建 Web 服务。在最后两种情况下,“发送”和对象是微不足道的,它相当于将其作为参数放入方法签名中。

You have plenty objects for serializing, such as binary, XML, JSON, but there is also a remoting approach, not to say that you can create web service. In two last cases, 'sending' and object is trivial and it amounts to putting it in a method signature as a parameter.

三生池水覆流年 2024-12-20 18:42:02

为什么你想自己通过套接字发送数据,而执行此操作的协议(高于 TCP)已经证明了它们的价值?

您必须创建一个协议来发送和接收数据,并实现该协议,在该协议中您将花费大量时间在以前做过且已经存在多年的事情上。更不用说花费时间调试一些无聊的东西,这些东西可以用于编程中更酷的部分,让语言和框架为“无聊”的部分工作,并将它们链接在一起以解决您遇到的问题。

您必须关心的事情是例如不同数据对象的分隔符和断开的连接(协议中的一种内容长度标头,用于告诉接收方需要多少数据)。

如果您要同时实现客户端和服务器,为什么不简单地使用 WCF 作为 SOAP、REST 或 JSON(如果对方这么说的话)或 Net.TCP 的包装器呢?

然后,您只需调用服务方法 MyObject[] GetObjects():框架将处理所有无聊的事情,并且您在客户端按原样接收 MyObject 数组。在后台,从 HTTP 标头到序列化,再到检测断开的连接和引发相关异常,一切都将为您完成。这可以节省大量的时间和麻烦。

或者,您可以使用纯 HTTP,创建一个小型 Web 应用程序,您可以在其中以您喜欢的序列化格式请求数据,并在通过 HttpClient

Why do you want to send data through sockets yourself, while protocols to do this (higher than TCP) already have proven their worth?

You'd have to create a protocol to send and receive the data, and implement this protocol, where you'll spend a lot of time on things that have been done before and have been around for many years. Not to mention the time spent debugging something boring that can be used for the cooler part of programming, putting a language and framework to work for the "boring" part, and link it together to solve the problem you're having.

Things you have to care about are for exapmple separators for different data objects and dropped connections (a kind of Content-Length header in your protocol to tell the receiving side how much data it has to expect).

Why don't you simply use WCF, as a wrapper for SOAP, REST or JSON (if the other side speaks that) or Net.TCP if you are to implement both client and server?

You then simply can call the service method MyObject[] GetObjects(): all the boring stuff will be dealt with by the framework, and you receive your MyObject array as-is on the client side. In the background everything from HTTP headers to serializing to detecting dropped connections and throwing relevant exceptions will be done for you. This saves serious time and trouble.

Or you could use plain HTTP, create a small web application where you can request the data in a serialized format you like and deserialize the data on the client side after receiving it through an HttpClient.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文