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

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

问题描述

我可以掌握 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():自动 bind() 将在第一个 send()/sendto()/recv()/recvfrom() 使用系统分配的本地端口号.

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.

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

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