Python总结之 recv与recv_from

编程入门 行业动态 更新时间:2024-10-26 13:34:24

<a href=https://www.elefans.com/category/jswz/34/1770869.html style=Python总结之 recv与recv_from"/>

Python总结之 recv与recv_from

在udp编程中,会发现,在利用socke接收数据时用的时recv_from,在tcp编程中用的是recv。
但是,细心的你会发现,udp中接收端口的时recv_rom,在tcp中则是accept,为什么呢?

因为recv的recvfrom是可以替换使用的,只是recvfrom多了两个参数,可以用来接收对端的地址信息,这个对于udp这种无连接的,可以很方便地进行回复。下面是源码:

def recvfrom(self, *args):if self._sslobj:raise ValueError("recvfrom not allowed on instances of %s" %self.__class__)else:return socket.recvfrom(self, *args)

而换过来如果你在udp当中也使用recv,那么就不知道该回复给谁了,如果你不需要回复的话,也是可以使用的。另外就是对于tcp是已经知道对端的,就没必要每次接收还多收一个地址,没有意义,要取地址信息,在accept当中取得就可以加以记录了。下面是源码:

def accept(self):"""accept() -> (socket object, address info)Wait for an incoming connection.  Return a new socketrepresenting the connection, and the address of the client.For IP sockets, the address info is a pair (hostaddr, port)."""fd, addr = self._accept()# If our type has the SOCK_NONBLOCK flag, we shouldn't pass it onto the# new socket. We do not currently allow passing SOCK_NONBLOCK to# accept4, so the returned socket is always blocking.type = self.type & ~globals().get("SOCK_NONBLOCK", 0)sock = socket(self.family, type, self.proto, fileno=fd)# Issue #7995: if no default timeout is set and the listening# socket had a (non-zero) timeout, force the new socket in blocking# mode to override platform-specific socket flags inheritance.if getdefaulttimeout() is None and self.gettimeout():sock.setblocking(True)return sock, addr

这里可以看到retrun的返回值有两个,一个sock,一个addr。

更多推荐

Python总结之 recv与recv_from

本文发布于:2023-07-28 18:08:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1270689.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Python   recv   recv_from

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!