【发布时间】:2014-08-08 04:52:15
【问题描述】:
我正在尝试开发可以将文件和字符串从客户端传输到服务器的客户端服务器应用程序。我是 TCP、套接字和服务器事务的新手。
客户端用Java编写,服务器端用C#编写
我在 Server(C#) 中尝试执行的操作,获取所有字节并将其转换为一个对象,因为我正在从客户端以 对象类型 发送所有对象。然后我想转换为文件或字符串
但是在这行代码中我遇到了一个错误
Object myObject = (Object)binForm.Deserialize(memStream);
服务器端:-
private void ClientHandler(object client)
{
int bytesRead = 0;
byte[] buffer = new byte[32];
tcpClient = (TcpClient)client;
clientStream = tcpClient.GetStream();
Console.WriteLine("Client Handler Started!");
while (true)
{
bytesRead = 0;
try
{
Console.WriteLine("Server waiting for commands\n");
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
while ((bytesRead = tcpClient.Client.Receive(buffer)) > 0)
{
Console.WriteLine("bytes received :- " + bytesRead);
memStream.Write(buffer, 0, bytesRead);
}
try
{
memStream.Position = 0;
Object myObject = (Object)binForm.Deserialize(memStream);
// After this cast it to String or File
}
catch(Exception exp)
{
Console.WriteLine(exp.ToString());
}
}
catch
{
//a socket error has occured
Console.WriteLine("a socket error has occured!!!");
break;
}
}
【问题讨论】:
-
您看到的错误是什么?
-
显示 catch 的内部异常?
-
异常是“在解析完成之前遇到流结束”
-
我以前从未真正尝试过,但我很确定您不能使用 .NET
BinaryFormatter反序列化使用 Java 序列化的对象。见stackoverflow.com/questions/17801967/… -
请添加以质疑您的可序列化对象。
标签: c# tcp binaryformatter