我有一个用 C# 制作的客户端/服务器应用程序。当我向服务器发送消息字符串时,它工作正常。但是我需要将(简单的)对象而不是字符串发送到服务器。但我不确定该怎么做。我目前为我的客户准备了这个:
我要发送的类:
[Serializable]
public class Actions
{
// Movement
public bool forward = false;
public bool left = false;
public bool backward = false;
public bool right = false;
}
然后我使用默认的 Send() 命令发送对象。但在那之前,我首先将 Actions 类转换为字节数组,如下所示:
public void SendObject ( object obj )
{
this.socket.Send ( this.ObjectToByteArray ( obj ) );
}
// Convert an object to a byte array
private byte[] ObjectToByteArray(object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
在服务器端我收到这样的数据(那是我被困在...):
public void OnDataReceived(IAsyncResult asyn)
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
try
{
// Complete the BeginReceive() asynchronous call by EndReceive() method
// which will return the number of characters written to the stream
// by the client
int iRx = socketData.m_currentSocket.EndReceive (asyn);
char[] chars = new char[iRx + 1];
// CONVERT THE BYTE ARRAY BACK TO AN OBJECT
//object Cls = this.ByteArrayToObject ( socketData.dataBuffer );
}
catch ( ... ) { }
}
我必须做什么才能访问服务器上的对象?显然,当我这样做时: Cls.forward;
然后它给了我一个错误,因为它不知道对象有什么属性。任何人都知道如何做到这一点??
最佳答案
将其从对象转换为Actions
:
object Cls = this.ByteArrayToObject ( socketData.dataBuffer );
Actions action = (Actions)Cls;
这是最简单的方法。您还应该添加异常处理、类型检查等。
关于c# - C#发送对象到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8545013/