2023年7月15日发(作者:)
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 om(self, *args)⽽换过来如果你在udp当中也使⽤recv,那么就不知道该回复给谁了,如果你不需要回复的话,也是可以使⽤的。另外就是对于tcp是已经知道对端的,就没必要每次接收还多收⼀个地址,没有意义,要取地址信息,在accept当中取得就可以加以记录了。下⾯是源码:def accept(self): """accept() -> (socket object, address info) Wait for an incoming connection. Return a new socket representing 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 = & ~globals().get("SOCK_NONBLOCK", 0) sock = socket(, type, , 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 eout(): cking(True) return sock, addr这⾥可以看到retrun的返回值有两个,⼀个sock,⼀个addr。
发布者:admin,转转请注明出处:http://www.yc00.com/web/1689410204a243537.html
评论列表(0条)