美文网首页
Python总结之 recv与recv_from

Python总结之 recv与recv_from

作者: Elvis_zhou | 来源:发表于2018-05-18 14:29 被阅读0次

    在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 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 = 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

          本文链接:https://www.haomeiwen.com/subject/udjgdftx.html