我正在尝试开发客户端服务器应用程序,该应用程序可以将文件和字符串从客户端转移到服务器。我是TCP,套接字和服务器事务的新手。
客户端用Java编写,服务器端用C#编写
我在服务器(C#)中尝试做的事情,获取所有字节并将其转换为Object,因为我在对象类型中从客户端发送所有对象。然后我想要转换为文件或字符串
但是在这行代码中我收到了错误
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;
}
}
答案 0 :(得分:2)
二进制格式化程序在二进制流上放置一个表示.NET类型的标头。您无法使用它将“对象”含义发送给非.net客户端。
相反,您必须序列化为XML或Json,并在您的客户端中提供本地模型和反序列化。