最近在写C#客户端发送int值给Java服务端的时候出现了问题。
搞了半天终于解决了。
问题原因在于字节数组顺序上。
在C#中一般会使用BitConverter.getBytes(i)方法获取字节数组。
现在我们自己处理下:
// 转换为Java格式的字节数组 static byte[] int2bytes(int n) { byte[] result = new byte[4]; result[0] = (byte)((n & 0xFF000000) >> 24); result[1] = (byte)((n & 0x00FF0000) >> 16); result[2] = (byte)((n & 0x0000FF00) >> 8); result[3] = (byte)((n & 0x000000FF)); return result; }
调用:
// socket发送int值 public void Send(int i) { client.Send(int2bytes(i)); }
OK,搞定了