尽管客户端停止发送消息,但服务器仍在运行 [英] Server still running despite client stopped sending messages

查看:37
本文介绍了尽管客户端停止发送消息,但服务器仍在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个循环中发送多个 UDP 数据报,并使用 sendmmsgrecvmmsg 系统调用接收它们.我的客户端代码是这样的:

I'm sending multiple UDP datagrams in a cycle and receiving them using sendmmsg and recvmmsg system calls. My client-side code is this :

struct mmsghdr *msgs;
struct iovec *iovecs;
while(interval){
  msgs = new struct mmsghdr[no_of_packets];
  iovecs = new struct iovec[no_of_packets];
  for(int i = 0;i < no_of_packets;i++){
    memset(&iovecs[i], 0, sizeof(iovecs[i]));
    iovecs[i].iov_base = (void *) to_string(i + 1).c_str();
    iovecs[i].iov_len = 1;
  }
  memset(msgs, 0, sizeof(msgs));
  for(int i = 0;i < no_of_packets;i++){
    msgs[i].msg_hdr.msg_iov = &iovecs[i];
    msgs[i].msg_hdr.msg_iovlen = 1;
  }
  ret_val = sendmmsg(socket_id, msgs, no_of_packets, 0);
  no_of_packets++;
  if(ret_val == -1)
    std::cerr << "Message sending failed.\n";
  else
    cout << ret_val << " messages sent\n";
  sleep(interval--);
}

客户端一直发送消息,直到间隔为正值.我的服务器端代码不断收到这些消息:

The client keeps sending messages until interval is positive. And my server side code keeps receiving these messages :

while(true){
  msgs = new struct mmsghdr[no_of_packets];
  iovecs = new struct iovec[no_of_packets];
  char buffers[no_of_packets][packet_size + 1];
  memset(msgs, 0, sizeof(msgs));
  for(int i = 0;i < no_of_packets;i++){
    iovecs[i].iov_base = buffers[i];
    iovecs[i].iov_len = packet_size;
    msgs[i].msg_hdr.msg_iov = &iovecs[i];
    msgs[i].msg_hdr.msg_iovlen = 1;
  }
  ret_val = recvmmsg(socket_id, msgs, no_of_packets, 0, NULL);
  no_of_packets++;
  if(ret_val < 0){
    break;
  }
  else{
    cout << ret_val << " messages received\n";
    for(int i = 0;i < ret_val;i++) {
      buffers[i][msgs[i].msg_len] = 0;
      printf("Trip %d : %s\n", i + 1, buffers[i]);
    }
  }
}

问题是即使在客户端发送完所有消息后,我的服务器也没有退出 while 循环.如何让服务器知道消息接收已完成?

The problem is my server doesn't exit from the while loop even after the client finishes sending all the messages. How can I make the server aware that the message receving has finished ?

推荐答案

问题是我的服务器即使在之后也没有退出 while 循环客户端完成发送所有消息.

The problem is my server doesn't exit from the while loop even after the client finishes sending all the messages.

UDP 服务器没有任何客户端连接的概念,UDP 服务器也不知道客户端何时完成发送".

UDP servers do not have any concept of a client connection, nor does a UDP server know when a client has "finished sending".

您的 recvmmsg 调用将等待客户端向其发送数据报.如果存在客户端可以告诉服务器退出的场景,则需要在应用程序协议级别完成.

Your recvmmsg call is just going to wait until a client sends it a datagram. If there's a scenario where your client can tell the server to exit, it needs to be done at the application protocol level.

这篇关于尽管客户端停止发送消息,但服务器仍在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆