在UDP套接字上使用sendto()/recvfrom()而不是connect()/send()/recv()的目的是什么? [英] What's the purpose of using sendto()/recvfrom() instead of connect()/send()/recv() with UDP sockets?

查看:447
本文介绍了在UDP套接字上使用sendto()/recvfrom()而不是connect()/send()/recv()的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以理解TCP与UDP的概念,但是我仍然不知道为什么有两种发送UDP数据包的方式,而且我仍然不知道对于bind()accept() ...

I can grasp the concept of TCP vs UDP, but still I don't know why are there 2 ways of sending UDP packets, and with that I still don't understand if this is absolutely necessary to bind() and accept()...

推荐答案

  1. accept()用于TCP.它与UDP无关.

  1. accept() is for TCP. It has nothing to do with UDP.

connect()到另一端没有任何作用,它只是使本地API知道您要向谁发送和接收来自谁.

connect() in UDP doesn't do anything to the other end, it just conditions the local API to know who you are sending to and receiving from.

如果您不知道或不关心,或者想使用同一套接字发送到多个目标,则不要使用connect(),而应使用sendto().同样用于接收.

If you don't already know that, or don't care, or want to send to multiple destinations with the same socket, you don't use connect(), you use sendto() instead. Similarly for receiving.

例如考虑一个UDP服务器.它会调用recvfrom(),,因此它将获取源地址信息,处理请求,创建响应,然后通过sendto().将其发送到该地址.在任何地方都没有涉及connect(),因此无法使用send()recv().

Consider a UDP server for example. It would call recvfrom(), so it would get the source address information, process the request, create the response, and send it to that address via sendto(). No connect() involved anywhere, ergo not possible to use either send() or recv().

仅需bind()一台服务器,因为客户端需要一个固定的端口号才能发送到该服务器.客户端完全不需要bind():使用系统分配的本地端口号在第一个send()/sendto()/recv()/recvfrom()上进行自动bind().

It is only necessary to bind() a server, because the clients need a fixed port number to send to. A client needn't bind() at all: an automatic bind() will take place on the first send()/sendto()/recv()/recvfrom() using a system-assigned local port number.

这篇关于在UDP套接字上使用sendto()/recvfrom()而不是connect()/send()/recv()的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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