C++ UDP RecvFrom、SendTo 不同的套接字 [英] C++ UDP RecvFrom, SendTo Different Sockets

查看:51
本文介绍了C++ UDP RecvFrom、SendTo 不同的套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照以下方案编写了一个多线程UDP服务器:

i wrote a multithreaded UDP server after the following scheme:

方案:1 个接收线程(多个Worker Threads,每个都有自己的Socket,没有bindend,只创建了Ipv4、UDP、Datagram)消息被推送到 1 个工人,然后继续执行,然后发送一个带有自己的套接字的应答.

Scheme: 1 Receiver Thread (Multiple Worker Threads, each has an own Socket, not bindend ,just created Ipv4, UDP,Datagram) Message gets pushed to 1 worker which then proceed's it and then sends an answere with its own socket.

问题:这在我自己的所有测试程序上都可以完美运行,但由于某些奇怪的原因,它不适用于我正在模拟服务器的旧软件.该软件使用异步 Wsa(重叠),但我仍然不明白为什么它不起作用.

Problem: This works perfectly on all my own test programs but for some odd reason it doesnt work with an old software for what i am emulating the server. The software uses async Wsa (overlapped), but i still doesn't get why it doesnt work.

困惑:如果我使用与用于在服务器端接收数据相同的套接字进行发送,它就可以工作.我不明白为什么,udp 是一种无连接协议,所以它如何检测不同的套接字?

Confusion: It works if I use the same socket for sending as i used for receiving the data on the serverside. I dont get why, udp is a connectionless protocol so how can it detect a different socket?

推荐答案

混淆:如果我使用与以前相同的套接字进行发送,它会起作用在服务器端接收数据.我不明白为什么,udp 是一个无连接协议如何检测不同的套接字?

Confusion: It works if I use the same socket for sending as i used for receiving the data on the serverside. I dont get why, udp is a connectionless protocol so how can it detect a different socket?

如果您查看发送的数据包的 UDP 标头,您会注意到它们包含UDP 源端口"字段.数据包的接收者可以检查该字段(通过 recvfrom())以找出发送机器上使用的发送 UDP 套接字的 UDP 端口(请注意,这与确定哪个端口的UDP 目标端口"字段不同数据包应传送到接收机器上).在您的情况下,您正在与之通信的程序可能正在查看该字段并根据该字段的值调整其行为.

If you look in the UDP headers of the packets you are sending you will notice that they contain a "UDP Source Port" field. That field can be examined by the receiver of the packet (via recvfrom()) to find out which UDP port the sending UDP socket used on the sending machine (note that this is different from the "UDP Destination Port" field that determines which port the packet should be delivered to on the receiving machine). It's possible that in your case, the program you are communicating with is looking at that field and adjusting its behavior based on that field's value.

如果您想知道如果您从未在发送 UDP 套接字上调用 bind(),那么该字段将被设置为什么,答案是操作系统将选择一个可用的 UDP 端口号进行发送(本质上是一个隐式绑定()).

If you're wondering what that field will be set to if you never called bind() on the sending UDP socket, the answer is that the OS will choose an available UDP port number to send from (essentially an implicit bind()).

这篇关于C++ UDP RecvFrom、SendTo 不同的套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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