gpt4 book ai didi

c# - 在 C# 中使用 Tcpclient 类发送和接收自定义对象

转载 作者:太空狗 更新时间:2023-10-29 17:34:41 26 4
gpt4 key购买 nike

我有一个客户端服务器应用程序,其中服务器和客户端需要通过网络发送和接收自定义类的对象。我正在使用 TcpClient 类来传输数据。我在发送方序列化对象并将生成的字节流发送到接收方。但是在接收方,当我尝试反序列化接收到的字节时,它会抛出序列化异常,详细信息是:

The input stream is not a valid binary format. The starting contents (in bytes) are: 0D-0A-00-01-00-00-00-FF-FF-FF-FF-01-00-00-00-00-00 ...

我序列化对象的服务器代码是:

byte[] userDataBytes;
MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(ms, new DataMessage());
userDataBytes = ms.ToArray();
netStream.Write(userDataBytes, 0, userDataBytes.Length);

反序列化的客户端代码是:

readNetStream.Read(readMsgBytes, 0, (int)tcpServer.ReceiveBufferSize);
MemoryStream ms = new MemoryStream(readMsgBytes);
BinaryFormatter bf1 = new BinaryFormatter();
ms.Position = 0;
object rawObj = bf1.Deserialize(ms);
DataMessage msgObj = (DataMessage)rawObj;

请帮助我解决这个问题,并可能建议使用 C# 中的 TcpClient 通过网络传输自定义类对象的任何其他方法。

谢谢,拉克什。

最佳答案

看看this code .它采用了稍微不同的方法。

上面链接给出的例子: - 注意:他遇到了另一个问题,他在这里解决了这个问题(keep-alive)。它位于初始示例代码之后的链接中。

要发送的对象类(记住[Serializable]):

[serializable] 
public class Person {
private string fn;
private string ln;
private int age;
...
public string FirstName {
get {
return fn;
}
set {
fn=value;
}
}
...
...
public Person (string firstname, string lastname, int age) {
this.fn=firstname;
...
}
}

类发送对象:

using System; 
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

class DataSender
{
public static void Main()
{
Person p=new Person("Tyler","Durden",30); // create my serializable object
string serverIp="192.168.0.1";

TcpClient client = new TcpClient(serverIp, 9050); // have my connection established with a Tcp Server

IFormatter formatter = new BinaryFormatter(); // the formatter that will serialize my object on my stream

NetworkStream strm = client.GetStream(); // the stream
formatter.Serialize(strm, p); // the serialization process

strm.Close();
client.Close();
}
}

接收对象的类:

using System; 
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

class DataRcvr
{
public static void Main()
{
TcpListener server = new TcpListener(9050);
server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream strm = client.GetStream();
IFormatter formatter = new BinaryFormatter();

Person p = (Person)formatter.Deserialize(strm); // you have to cast the deserialized object

Console.WriteLine("Hi, I'm "+p.FirstName+" "+p.LastName+" and I'm "+p.age+" years old!");

strm.Close();
client.Close();
server.Stop();
}
}

关于c# - 在 C# 中使用 Tcpclient 类发送和接收自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2316397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com