c# - 输入流不是有效的二进制格式 Tcp
问题描述
我有两种方法,它们的外观和工作方式非常相似。不知道为什么第一种方法有效,但第二种方法无效。第二次抛出异常“输入流不是有效的二进制格式 Tcp”此方法通过 tcp 将对象从客户端发送到服务器以及从服务器发送到客户端。同一个人可以告诉我我做错了什么吗?
public static void SendComput(NetworkStream stream)
{
string id = "1";
Byte[] datasend = System.Text.Encoding.ASCII.GetBytes(id);
BinaryFormatter formatter = new BinaryFormatter();
stream.Write(datasend, 0, datasend.Length);
Console.WriteLine("Sent: {0}", id);
while (true)
{
try
{
var data = new Byte[256];
String response = String.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
response = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", response);
}
catch (Exception e)
{
throw;
}
try
{
var t = GetComputeUnitsPerf();
var t2 = new Comp();
t2.ComputeTime = (uint)t.TimeMilisceoncd;
t2.DateCheck = t.Date;
t2.Id = Int32.Parse(id);
formatter.Serialize(stream,t2);
Console.WriteLine("Sent: {0}, {1}, {2}", t2.Id , t2.ComputeTime, t2.DateCheck);
Thread.Sleep(100);
}
catch (Exception e)
{
throw;
}
}
}
和服务器:
public void HandleDeivce3(Object obj)
{
TcpClient client = (TcpClient)obj;
var stream = client.GetStream();
Byte[] bytes = new Byte[256];
int i = 0;
string data = null;
BinaryFormatter formatter = new BinaryFormatter();
Task.Run(() =>
{
string hex = BitConverter.ToString(bytes);
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
while (true)
{
Thread.Sleep(10000);
Byte[] reply = System.Text.Encoding.ASCII.GetBytes("Send");
stream.Write(reply, 0, reply.Length);
Console.WriteLine("Send");
Thread.Sleep(200);
try
{
if (stream.CanRead)
{
var dataGet = (Comp)formatter.Deserialize(stream);
//Console.WriteLine("Sent: {0}, {1}, {2}", dataGet.Id, dataGet.ComputeTime, dataGet.DateCheck);
Console.WriteLine(dataGet.Id);
}
}
catch (Exception e)
{
throw;
}
}
});
}
我将 [Serializable] 添加到 Comp 类。
解决方案
推荐阅读
- python - 从集合中随机选择一个/多个函数并应用组合
- r - 提取r中整个数据帧范围内的值
- reactjs - 使用 react-bootstrap 设计一个漂亮的用户帐户仪表板
- javascript - 12 小时 Javascript 时钟显示 24 时间,上午/下午错误
- javascript - 我编写了一个 nodejs 应用程序来操作 Google 表格。如何将其转换为附加组件?
- asp.net-core - blazor webassembly System.Net.Http.HttpRequestException:响应状态码不表示成功:400(错误请求)
- python - socket.accept() 在类中运行时返回无效参数
- python - 使用 pip 时找不到 Pyglet 导入
- python - 使用 Keras 实现神经网络
- javascript - jquery限制页面上显示的json数据量