停止在UDP服务器中接收未知数量的数据包 [英] stop receiving unknown number of packets in UDP server

查看:114
本文介绍了停止在UDP服务器中接收未知数量的数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!

我有一台UDP服务器(附带源代码)。 cout<<end;行不执行。收到数据包并将其打印到屏幕上,但在关闭客户端套接字后(在客户端代码中)服务器不会从循环中退出。

任何人都可以帮助我吗?



Hi!
I have a UDP server (source code is attached). "cout << "end";" line doesn't execute. Packets are received and are printed to screen but after closing client socket (in client code) server does not exit from while loop.
Can anyone help me?

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include "iostream"
#include "conio.h"
#include "windows.h"
#include "winsock2.h"
#include "string"

#pragma comment(lib, "Ws2_32.lib")

using namespace std;

int main()
{
    WSAData wsaData;
    WORD DllVersion = MAKEWORD(2,2);
    int startup_RetVal = WSAStartup(DllVersion, &wsaData);
    SOCKET sSocket = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    SOCKADDR_IN addr;
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    addr.sin_family = AF_INET;
    addr.sin_port = htons(2222);
    bind(sSocket,(SOCKADDR*)&addr, sizeof(addr));
    char buf[400] = {0};
    while (recvfrom(sSocket, buf, 400, NULL, NULL, NULL) > 0)
    {
	cout << buf;
    }
    cout << "end";
    _getch();
    return 0;
}

推荐答案

UDP是一种无连接协议。因此,您的服务器将无法检测到客户端已关闭其连接,并且 recvfrom 将永远不会返回值为零。



如何解决这个问题取决于你想做什么。您可以切换到面向连接的协议或实现自己的传输协议,将特定数据包作为挂断命令处理。
UDP is a connectionless protocol. So your server will not detect that the client has closed his connection and recvfrom will never return with a value of zero.

How to solve this problem depends on what you want to do. You can switch to a connection oriented protocol or implement your own transfer protocol that handles specific packets as "hangup" command.


这篇关于停止在UDP服务器中接收未知数量的数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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