简体   繁体   English

接收多消息套接字编程C

[英]Receive the multiple message socket programming C

Hi I new to socket programming C. Now I working on chat program and I successful can sending and receiving message but the problem is when client request to send list of user that client online and once server send message back to client the message is successful print the list of current connected client but once it display it not going out of loop. 嗨,我是套接字编程C的新手。现在,我正在使用聊天程序,可以成功发送和接收消息,但是问题是,当客户端请求发送客户端在线用户列表时,一旦服务器将消息发送回客户端,则消息成功打印当前连接的客户端列表,但是一旦显示,它就不会退出循环。 below is only one section of the code. 下面只是代码的一部分。

server side (server.c) 服务器端(server.c)

pthread_mutex_lock(&list_mutex);
   for(i =0; i < NotEndOfList; i++)
   {

    sprintf(message_replay, "Server: %s \n", usersList[i].name); 
    write(sock , message_replay , strlen(message_replay));  

  }
  pthread_mutex_unlock(&list_mutex);

Client side (Client.c) 客户端(Client.c)

int i =0;
          while(i < NotEndOfList)
         {
            if( recv(sock , server_reply , 2000 , 0) < 0)
            {
              puts("recv failed");
              break;
            }
         i++;

        puts(server_reply);
      }

Sample Output 样本输出

    User A -->:
    //List 
    User A
    User B
    User C
    // Loop

Correct Sample Output 正确的样品输出

User A -->:
//List
User A
User B
User C
User A -->:

Thank you very much 非常感谢你

This solution can be used if all messages are the same size. 如果所有消息的大小均相同,则可以使用此解决方案。 I don't know the size of your message_replay , lets just say its of type char[256] . 我不知道您message_replay的大小,只说其类型为char[256]

At the server 在服务器上

Instead of using strlen() you can always send 256 bytes. 不必使用strlen()您始终可以发送256个字节。 The client will just ignore all trailing characters after the null terminator. 客户端将忽略空终止符之后的所有尾随字符。

write(sock , message_replay, 256); // or sizeof(message_replay) if it's static

At the client 在客户处

Client should then expect all messages to be 256 bytes long. 然后,客户端应期望所有消息的长度为256个字节。 A loop runs untill all 256 characters have been received, and appends to receive_buffer[] every loop. 运行一个循环,直到接收到所有256个字符,并在每个循环后追加到receive_buffer[] Counters keep track of how many bytes we have received and how many we are short of. 计数器跟踪我们收到了多少字节以及缺少多少字节。

for (int i = 0; i < NotEndOFList; i++) {
    char receive_buffer[256];
    int received_bytes = 0;
    int remaining_bytes = sizeof(receive_buffer);

    while (remaining_bytes > 0) {
        int res = recv(sock , &receive_buffer[received_bytes] , remaining_bytes, 0);
        if (res < 0) {
            puts("recv failed");
            break;
        }
        received_bytes += res;
        remaining_bytes -= res;
    }

    puts(receive_buffer);
}

PS! PS! I've not tested, let me know how it runs if you decide to use it. 我尚未测试,如果您决定使用它,请告诉我它如何运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM