客户端代码:
void OnConnectSendMessageToServer(object obj)
{
Socket client_socket = (Socket)obj;
print("程序运行到此");
CMD_C_ConnectData conData = new CMD_C_ConnectData();
byte[] data = new byte[1024];
string msg = "123456";
conData.buffer = Encoding.UTF8.GetBytes(msg);
conData.nLen = conData.buffer.Length;
conData.dataStatus = CMD_C_DataStatus.SUB_C_NULL;
try
{
IntPtr strucPtr = Marshal.AllocHGlobal(Marshal.SizeOf(conData));
Marshal.StructureToPtr(conData,strucPtr,false);
Marshal.Copy(strucPtr,data,0,Marshal.SizeOf(conData));
Marshal.FreeHGlobal(strucPtr);
IntPtr dataPtr = Marshal.AllocHGlobal(conData.buffer.Length);
Marshal.Copy(conData.buffer,0,dataPtr,conData.buffer.Length);
Marshal.Copy(dataPtr, data, Marshal.SizeOf(conData), conData.buffer.Length);
Marshal.FreeHGlobal(dataPtr);
for (int i = 0; i < data.Length; i++)
{
print(i + " " + data[i]);
}
client_socket.Send(data, data.Length, SocketFlags.None);
}
catch (Exception ex)
{
print(ex.Message);
}
}
服务端代码
byte[] buffer = new byte[1024];
int num = clients.Receive(buffer);
if (num <= 0) return;
recvData sRecvData = new recvData();
int size = Marshal.SizeOf(sRecvData);
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.Copy(buffer,0,structPtr,size);
try
{
sRecvData = (recvData)Marshal.PtrToStructure(structPtr, typeof(recvData));
Marshal.FreeHGlobal(structPtr);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message+"fadsfadsfadfasdfasd");
throw;
}
其中在sRecvData = (recvData)Marshal.PtrToStructure(structPtr, typeof(recvData));调试下报错,错误信息为:
“System.AccessViolationException”类型的第一次机会异常在 mscorlib.dll 中发生
其他信息: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
这种错误,你先调整项目属性,生成里面改成x86试试。
已更改