客户端服务器 - (TCP)

时间:2011-03-07 12:37:22

标签: visual-c++ tcp

我正在尝试将一些文本从客户端发送到服务器。 我还想显示时间戳,以便通知收到消息的时间。 当我尝试发送时间时,它会发送一个空白。但是显示其余的字符串。

这是我从客户端发送的代码:

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));
    }

}

以及如何在服务器控制台上打印:

                  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");

1 个答案:

答案 0 :(得分:1)

应将tcp连接视为字节流。您将其视为具有类型信息的对象流。

在3发送之后,已经传输的字节将是例如。

ABC \ 0UserName \ 0 \ 0Time \ 0 - 总共19个字节。

然后你读取99个字节,并将所有数据存储到“文本”中,流中没有任何内容留下来进行下一次读取。

您需要在文本本身之前发送文本的长度,或者您需要在接收端读取“数据”并扫描例如一个0终结符,用于提取流的3个逻辑元素。

相关问题