Johan
Johan

Reputation: 495

Send message from java to c++, weird stuff received in c++ client

I've studied Java now for almost 8 months and decided to learn some c++ on the side.

I have a server in Java which waits for a client to connect (client in C++).

What I'm doing in the java server when client connects:

  1. Type a message on the keyboard.
  2. Convert the text (String) to bytes.
  3. Send the bytearray to C++ client.

What the C++ Client is doing when it connects:

  1. Declare a char array named "buff".
  2. Receive the message from Java server.
  3. Print the message if there are no errors while receiving.

The relevant code in Java:

String message;
        byte[] byteArray = new byte[1024];

        while (true) {
            System.out.println("Enter message: ");
            message = sc.nextLine();    // Enter message
            byteArray = message.getBytes("UTF-8");  // Get bytes of message
            out.write(byteArray);   // Send the Message
        }

The relevant code in C++:

std::cout << "Connected!";

while (true)
{
    char buff[1024];

    if (what = recv(u_sock, buff, sizeof(buff), 0) < 0)
    {
        cout << "Error receiving message " << WSAGetLastError() << endl;
    }
    else
    {
        cout << "Message: " << buff << endl;
    }
}

The actual problem: When I send the String "asd" from Java, I receive the "asd" in C++, AND a smiley, and the text winsock2.0. And sometimes I just receive the previous message instead of the current message sent. What could possibly be the problem? When I tried sending message from C++ client to Java server, it worked.

Upvotes: 0

Views: 766

Answers (2)

user207421
user207421

Reputation: 310916

I receive the "asd" in C++, AND a smiley, and the text winsock2.0.

No . That stuff was already in the buffer. The problem here is that you're ignoring the length returned by recv(). You must use that to delimit how much of buff you print, which thankfully I've forgotten how to do in C++ streams.

You must also check it for zero, meaning that the peer closed the connection. In both the error and the zero cases you should also close the socket and break out of the loop, unless the error was EAGAIN/EWOULDBLOCK.

Upvotes: 2

StenSoft
StenSoft

Reputation: 9609

The received data are not NULL-terminated. To fix that, you should NULL-terminate them:

if ((what = recv(u_sock, buff, sizeof(buff)-1, 0)) < 0)
{
    ⋮
}
else
{
    buff[what] = 0;
    cout << buff << endl;
}

Upvotes: 2

Related Questions