Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C客户端和Java服务器之间的通信出错_Java_C_Sockets - Fatal编程技术网

C客户端和Java服务器之间的通信出错

C客户端和Java服务器之间的通信出错,java,c,sockets,Java,C,Sockets,我想向服务器发送一个整数,递增它,然后将新的数字和随机字符串发送回客户端。我使用这个代码 int value = htons( 4 ); int reply = 0; send( to_server_socket, &value, sizeof( value ),0 ); recv( to_server_socket, &reply, sizeof( reply ), 0 ); printf( "got reply: %d\n", ntohs( reply ) ); 服务器代码

我想向服务器发送一个整数,递增它,然后将新的数字和随机字符串发送回客户端。我使用这个代码

int value = htons( 4 );
int reply = 0;
send( to_server_socket, &value, sizeof( value ),0 );
recv( to_server_socket, &reply, sizeof( reply ), 0 );
printf( "got reply: %d\n", ntohs( reply ) );
服务器代码

DataInputStream din = new DataInputStream(socket.getInputStream());
        int ClientNumber= din.readInt();
        System.out.println(ClientNumber);


        ClientNumber++;
       DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
       dos.writeInt(ClientNumber);

       String randomString= getRandomValue(10,20);
       dos.writeUTF(randomString);
但是服务器没有收到4,而是收到262144,并且客户端中的回复仍然是0。我在服务器上也有一个错误

位于的java.io.EOFException java.io.DataInputStream.readUnsignedShort(DataInputStream.java:323) 在java.io.DataInputStream.readUTF(DataInputStream.java:572)中 readUTF(DataInputStream.java:547)位于 ServiceRequest.run(ServiceRequest.java:41)位于 Executors$RunnableAdapter.call(Executors.java:439) 位于java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) 在java.util.concurrent.FutureTask.run(FutureTask.java:138)中 java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) 运行(Thread.java:680)

编辑:


它与htonl一起工作,我得到int,但对于字符串,我得到的是数字而不是字符

您正在使用
htons
函数将
int
值转换为网络字节顺序

函数
htons
定义用于将小端主机上的字节重新排列为网络字节顺序(big-endian),Java始终是big-endian

但是这个函数转换的是16位的值,而不是32位的值。以下是一些要点:

4      = 00000100 00000000 00000000 00000000 (2^2) (little-endian)
262144 = 00000000 00000100 00000000 00000000 (2^18) (big-endian)
尝试使用该函数,将32位
int
值转换为网络字节顺序。那么结果应该是这样的

4      = 00000100 00000000 00000000 00000000 (2^2) (little-endian)
4      = 00000000 00000000 00000000 00000100 (2^2) (big-endian)

262144是十六进制0x00040000,因此某些内容会更改您的字节顺序。

您已经问过这个问题。你在这里发布的代码显示,你错过了我先前答案中的最后编辑。返回并重新阅读此处的编辑: