0

;)

I write a chat program with c++ server and java client.

The code of the function that responsible to receiving messages from the client is:

void *recieve(void* *v)
{
    while (true)
    {
        bzero(buffer, 256);
        n = read(socketfd, buffer, 256);
        if (n < 0)
            exit(1);
        printf("Client: %s", buffer);
    }
}

the code of the function thar responsible to send messages to the server is just:

ps.println(msg);

where ps is a printstream.

When I send a message to the server, say "hello world" the c++ server print: "Client: hello worldClient".

I would appreciate if someone could help me with this. (I apologize if my English is not good) thanks!

Ido Ikar
  • 121
  • 1
  • 1
  • 7
  • Have you tried using write and writing only the number of bytes read ? And as Joachim said, don't forget the null terminating byte x) – Naliwe Sep 11 '16 at 14:45
  • By the way, you miss an important case in your error checking of the `read` call: You do not handle disconnects properly. – Some programmer dude Sep 11 '16 at 14:46
  • @JoachimPileborg doesn't [`bzero()`](http://man7.org/linux/man-pages/man3/bzero.3.html) ensure that the null terminator will be there if less than 256 bytes are received ? – Christophe Sep 11 '16 at 15:05

1 Answers1

2

The read() function will return 0 when it reaches the end of file.

So in your case, there is a first loop iteration that receives "Hello world", then there's one more iteration, that will receive nothing but read() returns 0. So "Client :" is displayed with an empty string.

In addition, be aware that:

  • with socket based communication, it is not guaranteed that one read() on the server side will correspond to one println() on the client side. So for longer messages, you'll risk to receive it in pieces. On the output you'd then see several "Client" within the message text.
  • the line separator sent on the java side might not necessarily correspond to the line separator expected on the server side, expect if you're working cross-platform.
Community
  • 1
  • 1
Christophe
  • 68,716
  • 7
  • 72
  • 138