Pavitar
Pavitar

Reputation: 4374

Client Server -(TCP)

I am trying to send some text from the client's end to the server. I also want to display time stamps,so as to notify the time at which the message was received. When I try sending the time it sends a blank.However the rest of the string gets displayed.

Here my code for sending from the client's end:

void ClientSock::OnConnect(int nErrorCode)
{
    // TODO: Add your specialized code here and/or call the base class
    if(nErrorCode)
    {
        AfxMessageBox(_T("Connection Failure."));
        Close();
    }
    else
    {
        time_t clock;
        time(&clock);
        char min[30] = {0};
        char s = ctime_s(min,sizeof(min),&clock);
        char text[100] = {0};
        char user[10] = {"UserName"};
        int n = m_pDlg->GetDlgItemText(ID_REQUEST,text, 100);
        Send(text,n);
        Send(user,sizeof(user));
        Send(min,sizeof(min));
        //m_pDlg->SetDlgItemText(ID_REQUEST,min);
        AfxMessageBox(_T(min));
    }

}

and heres how im printing at the Server's console:

                  SOCKET client;
            char text[100] = {0};
            char user[10] = {0};
            char min[30] = {0};
            int n,m;
            //(here the server waits for the client and accepts connection requests) 
            client  = accept(server, NULL, NULL);
            //(receiving text from the client)

            n = recv(client, text, 99, 0);          
            recv(client, user, 9, 0);       
            m = recv(client, min, 29, 0);       

            if(n > 0 && m > 0)
            {
                printf("%s:: %s:%s\n",min,user,text);
            }               
            else
                printf("ERROR:Communication Failure.\n");

Upvotes: 0

Views: 295

Answers (1)

Erik
Erik

Reputation: 91270

A tcp connection should be treated as a stream of bytes. You're treating it as if it was a stream of objects with type information.

After your 3 Send's, the bytes that have been transferred would be e.g.

ABC\0UserName\0\0Time\0 - A total of 19 bytes.

Then you read 99 bytes, and get all of the data stored into "text", with nothing left in the stream for your next reads.

You'll need to either send the length of the text before the text itself, or you'll need to read "data" on the receiving end and scan for e.g. a 0-terminator to extract the 3 logical elements of the stream.

Upvotes: 1

Related Questions