我認爲這可能是字節排序,但它看起來不像它。 我不知道還有什麼可以的。從Java客戶端通過套接字寫入int到c服務器
在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如果這是可能的。
剛剛嘗試過,輸出相同 – Nicolas
您的代碼不檢查可以通過read()返回的'result = -1'。 –
是的,我想我會省略一些錯誤檢查這個問題。 – Nicolas