我认为这可能是字节顺序,但看起来并非如此。 我不确定它还会是什么。
Linux 上的 Java 客户端
private static final int CODE = 0;
Socket socket = new Socket("10.10.10.10", 50505);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeInt(CODE);
C 服务器也在 Linux 上
int sd = createSocket();
int code = -1;
int bytesRead = 0;
int result;
while (bytesRead < sizeof(int))
{
result = read(sd, &code + bytesRead, sizeof(int) - bytesRead);
bytesRead += result;
}
int ntolCode = ntohl(code); //test for byte order issue
printf("\n%i\n%i\n%i\n", code, ntolCode, bytesRead);
打印出:
-256
16777215
4
不知道还可以尝试什么。
解决方案
这个解决方案对我来说一点也不直观,但无论如何还是感谢您的反对票!
Java端
Socket socket = new Socket("10.10.10.10", 50505);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
int x = 123456;
ByteBuffer buff = ByteBuffer.allocate(4);
byte[] b = buff.order(ByteOrder.LITTLE_ENDIAN).putInt(x).array();
out.write(b);
C面
int sd = createSocket();
char buff[4];
int bytesRead = 0;
int result;
while (bytesRead < 4){
result = read(sd, buff + bytesRead, sizeof(buff) - bytesRead);
if (result < 1) {
return -1;
}
bytesRead += result;
}
int answer = (buff[3] << 24 | buff[2] << 16 | buff[1] << 8 | buff[0]);
如果有人有任何东西,我仍然对更简单的解决方案感兴趣,如果可能的话最好使用 BufferedWriter。
最佳答案
问题出在这里:
&code + bytesRead
这将增加 code
的地址步长为 4 ( sizeof code
),而不是 1。您需要一个字节数组,或一些类型转换。
关于java - 通过套接字将 int 从 Java 客户端写入到 C 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38165142/