0

I send an integer from a C client to a java server and it worked perfectly. But when i tried to do the same thing with a string i got and error this is the client code to send the String

char clientString[30];

    printf("String to send : \n");

        if( send( to_server_socket, &clientString, sizeof( clientString ), 0 ) != sizeof( clientString ) )
        {
            printf( "socket write failed");
            exit( -1 );
        }

And the java code to read it

DataInputStream din = new DataInputStream(socket.getInputStream());
          String clientString=din.readUTF();
           System.out.println(clientString);

Error

java.io.EOFException at java.io.DataInputStream.readFully(DataInputStream.java:180) at java.io.DataInputStream.readUTF(DataInputStream.java:592) at java.io.DataInputStream.readUTF(DataInputStream.java:547) at ServiceRequest.run(ServiceRequest.java:43) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at java.lang.Thread.run(Thread.java:680)

EDIT :I tried using din.readLine(),I don't have the error anymore but if i type fffffff12 on the client i got fffffff12`?7E^Ê?h in the server

4

3 回答 3

1

您发送数组中的所有数据clientString,无论输入的实际长度是多少。正确终止字符串,只发送例如strlen(clientString)字节。

于 2013-05-04T17:51:39.907 回答
0

也许问题是在客户端您正在编写 ASCII 字符串,但在服务器端您正在读取 UTF,请尝试将数据读取为 ASCII,如果可能,请提及发生的异常。此方法可以引发两个异常:1- IO 异常或 2- EOF 异常。

于 2013-05-04T17:38:00.510 回答
0

readUTF不只是从套接字读取字节。它首先读取字符串的长度(作为 16 位整数),然后读取字符串。问题是您发送的不是readUTF成功工作所需的。

正如 Joachim Pileborg 所指出的,您还发送了整个 30 个字节clientString(包括未明确设置的任何剩余字节)。你应该像这样发送它:

send(to_server_socket, clientString, strlen(clientString), 0);
于 2013-05-04T18:06:33.927 回答