Question

I'm trying to make a program that sends information (set of characters) to another program (client/sever) with winsock for my school project.

the message I send is received on the other side, but with extra characters at the end. I.E. if I wanted to send "hallo" I receive "hallod3" or some random symbols.

P.S: the message is sent from the Client to the Server

here's my code on the server:

 char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;

  do {

        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);     
        if (iResult > 0) {
            ShowMessage(recvbuf);
        }

        else if (iResult == 0)
            ShowMessage("Connection closing...\n");
        else  {
            ShowMessage("recv failed with error: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            ShowMessage("send failed");
        }
     } while (iResult > 0);

and here's the client:

 char sendbuf[DEFAULT_BUFLEN];

  iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        ShowMessage("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
       ShowMessage("send failed");
    }

DEFAULT_BUFLEN is defined (length of the message), ShowMessage() is a function from VCL component (I'm using Borland C++ Builder) that takes a string and displays it.

P.S: I made sure of the string 'sendbuf' in the client and there's no extra character, I even add '\0' in the end of the string.

what could be the problem here ?

Was it helpful?

Solution

It isn't 'received with extra characters'. It's just that you're ignoring iResult when displaying the receive buffer. It's only valid for iResult bytes, not the whole thing.

OTHER TIPS

the count returned by strlen does not include the '\0' character, so the '\0' character does not get sent. Also, you are not guaranteed to received the whole message in one recv call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top