recv和UDP套接字时出现问题

recv和UDP套接字时出现问题

本文介绍了使用Connect(),send(),recv和UDP套接字时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的Uni作业,我必须创建一个快速动作节奏的网络游戏,因此选择使用UDP而不是TCP.我知道在UDP和TCP编程方面的许多差异,并且已经阅读了有关Winsock的MSDN文档的大部分相关部分.在MSDN上,它声明通过connect()函数创建UDP套接字应将套接字绑定到指定的地址和端口,因此可以对创建的套接字使用send()和recv()函数.

For my Uni assignment I have to create a fast action paced networked game and so have chosen to use UDP as opposed to TCP. I am aware of a lot of the differences in programming both UDP and TCP and have read through most of the relevant parts of MSDN's documentation on winsock. On MSDN it states that creating a UDP socket via the connect() function should bind the socket to the address and port specified and as a result be able use the send() and recv() functions with the created socket.

对于我的应用程序,我创建一个客户端并使用具有回送地址的connect(),该地址通过send()函数发送许多数据包.客户端在调用select()之后,然后接收它发出的数据包.但是,我从recv()函数得到的结果是SOCKET_ERROR,使用WSAGetLastError()的错误描述是远程主机强行关闭了现有连接".

For my application I create a client and use connect() using the loopback address which sends a number of packets via the send() function. The client, after calling select(), then receives the packets it sent out. However the result I get from the recv() function is SOCKET_ERROR and the error description using WSAGetLastError() is "An existing connection was forcibly closed by the remote host".

如果我使用bind()函数并使用sendto()通过回送地址发送数据,那么我会接收recv()数据包,而不会出现任何错误...有人知道为什么connect()函数没有发挥作用吗?应该可以做到吗,并且有人可以通过connect()函数使用UDP套接字吗?

If i use the bind() function and use sendto() to send data over the loopback address, I recv() packets without any errors... Does anyone know why the connect() function is not doing what it is supposed to do, and has anyone been able to use UDP sockets with the connect() function?

推荐答案

如果您希望程序接收UDP数据包,则需要调用bind().connect()仅在调用send()时设置套接字将数据包发送到的地址;它不会将套接字与要在其上接收的本地UDP端口相关联;为此,您必须调用bind().

You will need to call bind() if you want your program to receive UDP packets. connect() only sets the address that the socket will send packets to if you call send(); it does not associate the socket with a local UDP port to receive on; for that you must call bind().

这篇关于使用Connect(),send(),recv和UDP套接字时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 19:05