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

有帮助吗?

解决方案 2

readUTF doesn't just read bytes from a socket. It starts by reading the length of the string (as a 16-bit integer) and then reading the string. The problem is that what you send is not what is required for readUTF to work successfully.

As Joachim Pileborg noted, you are also sending the entire 30 bytes of clientString (including any remaining bytes that were not explicitly set). You should send it like this instead:

send(to_server_socket, clientString, strlen(clientString), 0);

其他提示

You send all of the data in the clientString array, no matter how long the input really is. Terminate the string properly and only send e.g. strlen(clientString) bytes instead.

Maybe the problem is that on the client side you are writing ASCII string but on the server side you are reading UTF, try to read the data as ASCII, as well if possible please mention the exception that occurred. This method can raise two exceptions: 1- An IO Exception or 2- An EOF exception.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top