user2350329
user2350329

Reputation: 3

Socket C client and Java server can send only one String

My Java server sends an Integer and a String (to a C client):

   DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

   dos.writeInt(ClientNumber); //send the Integer

   String randomString= getRandomValue(10,20);
   dos.writeUTF(randomString);  //send the String
   String clientString=din.readLine();

The C code for the client that's reading them is:

if( recv( to_server_socket, &reply, sizeof( reply ), MSG_WAITALL ) != sizeof( reply ) )
    {
        printf( "socket read failed");
        exit( -1 );
    }
char buf[50];
int byte_count;
byte_count = recv(to_server_socket, buf, sizeof buf, 0);
printf("recv()'d %d bytes of data in buf\n", byte_count)

Until here, it works fine.

Now, I want to send another String to the Client. So, I tried just adding the line:

dos.writeUTF("blabla");

It's still working and when I tried to get the client to read it, I added:

byte_count2 = recv(to_server_socket, buf2, sizeof buf2, 0);
   printf("recv()'d %d bytes of data in buf\n", byte_count2);

And it doesn't work. The client receives the number and the first String but it doesn't send anything and doesn't receive the "blabla" string. I'm not sure if the problem is in the client or the server.

Can anyone explain to me what I'm doing wrong?

Upvotes: 0

Views: 962

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533500

You are mixing your protocols. I suggest you use either binary or text wire format. It's not clear which one you are trying to use.

I suggest text wire format as it is easier to work with in this case. i.e. don't DataInputStream or DataOutputStream as these are for binary formats.

Instead you can use BufferedReader for reading lines of text and PrintWriter for writing lines of text. You can test your server works by connecting to it with telnet i.e. if it doesn't work with telnet, it won't work with C.

Once this is working, get your C client to work as well. BTW You shouldn't assume that one write translates to one read. You are writing a Stream of data, not messages.

Upvotes: 1

Juned Ahsan
Juned Ahsan

Reputation: 68715

Try closing your dos(DataOutpuStream) after every write. You may try to check first if flush helps.

Upvotes: 1

Related Questions