设为首页 收藏本站
查看: 291|回复: 0

[经验分享] Python socket简介

[复制链接]

尚未签到

发表于 2017-4-23 12:59:46 | 显示全部楼层 |阅读模式
自豪地使用dir和help.

Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> dir(socket.socket)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_sock', 'accept', 'bind', 'close', 'connect', 'connect_ex', 'dup', 'family', 'fileno', 'getpeername', 'getsockname', 'getsockopt', 'gettimeout', 'listen', 'makefile', 'proto', 'recv', 'recv_into', 'recvfrom', 'recvfrom_into', 'send', 'sendall', 'sendto', 'setblocking', 'setsockopt', 'settimeout', 'shutdown', 'type']
>>> help(socket.socket)
class _socketobject(__builtin__.object)
| socket([family[, type[, proto]]]) -> socket object
|  
| Open a socket of the given type. The family argument specifies the
| address family; it defaults to AF_INET. The type argument specifies
| whether this is a stream (SOCK_STREAM, this is the default)
| or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,
| specifying the default protocol. Keyword arguments are accepted.
|  
| A socket object represents one endpoint of a network connection.
|  
| Methods of socket objects (keyword arguments not allowed):
|  
| accept() -- accept a connection, returning new socket and client address
| bind(addr) -- bind the socket to a local address
| close() -- close the socket
| connect(addr) -- connect the socket to a remote address
| connect_ex(addr) -- connect, return an error code instead of an exception
| dup() -- return a new socket object identical to the current one

  • | fileno() -- return underlying file descriptor
    | getpeername() -- return remote address

  • | getsockname() -- return local address
    | getsockopt(level, optname[, buflen]) -- get socket options
    | gettimeout() -- return timeout or None
    | listen(n) -- start listening for incoming connections
    | makefile([mode, [bufsize]]) -- return a file object for the socket

  • | recv(buflen[, flags]) -- receive data
    | recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)
    | recvfrom(buflen[, flags]) -- receive data and sender's address
    | recvfrom_into(buffer[, nbytes, [, flags])
    | -- receive data and sender's address (into a buffer)
    | sendall(data[, flags]) -- send all data
    | send(data[, flags]) -- send data, may not send all of it
    | sendto(data[, flags], addr) -- send data to a given address
    | setblocking(0 | 1) -- set or clear the blocking I/O flag
    | setsockopt(level, optname, value) -- set socket options
    | settimeout(None | float) -- set or clear the timeout
    | shutdown(how) -- shut down traffic in one or both directions
    >>> help(socket.getaddrinfo)
    Help on built-in function getaddrinfo in module _socket:
    getaddrinfo(…)
    getaddrinfo(host, port [, family, socktype, proto, flags])
    -> list of (family, socktype, proto, canonname, sockaddr)
    Resolve host and port into addrinfo struct.

    Simple Demo:

    # Echo server program
    import socket
    HOST ='' # Symbolic name meaning all available interfaces
    PORT =50007 # Arbitrary non-privileged port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    print'Connected by', addr
    while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
    conn.close()


    # Echo client program
    import socket
    HOST ='' # The remote host
    PORT =50007 # The same port as used by the server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    s.sendall('Hello, world')
    data = s.recv(1024)
    s.close()
    print'Received', repr(data)

    1、setblocking(0 | 1) -- set or clear the blocking I/O flag
    引用
    Set blocking or non-blocking mode of the socket: if flag is 0, the socket is set to non-blocking, else to blocking mode. Initially all sockets are in blocking mode. In non-blocking mode, if a recv() call doesn’t find any data, or if a send() call can’t immediately dispose of the data, a error exception is raised; in blocking mode, the calls block until they can proceed. s.setblocking(0) is equivalent to s.settimeout(0.0); s.setblocking(1) is equivalent to s.settimeout(None).

    2、setsockopt(level, optname, value) -- set socket options
    引用
    Set the value of the given socket option (see the Unix manual page setsockopt(2)). The needed symbolic constants are defined in the socket module (SO_* etc.). The value can be an integer or a string representing a buffer. In the latter case it is up to the caller to ensure that the string contains the proper bits (see the optional built-in module struct for a way to encode C structures as strings).

    套接字机制提供两个套接字选项接口来控制套接字行为。一个用来设置,一个用来获取。(getsockopt)
    3、settimeout(None | float) -- set or clear the timeout
    引用
    Set a timeout on blocking socket operations. The value argument can be a nonnegative float expressing seconds, or None. If a float is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. Setting a timeout of None disables timeouts on socket operations. s.settimeout(0.0) is equivalent to s.setblocking(0); s.settimeout(None) is equivalent to s.setblocking(1).

    4、shutdown(how) -- shut down traffic in one or both directions
    引用
    Shut down one or both halves of the connection. If how is SHUT_RD, further receives are disallowed. If how is SHUT_WR, further sends are disallowed. If how isSHUT_RDWR, further sends and receives are disallowed. Depending on the platform, shutting down one half of the connection can also close the opposite half (e.g. on Mac OS X, shutdown(SHUT_WR) does not allow further reads on the other end of the connection).

    资料参考:
    http://docs.python.org/2/library/socket.html

  • 运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
    2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
    3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
    4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
    5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
    6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
    7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
    8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

    所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-368188-1-1.html 上篇帖子: Python 日期转换 下篇帖子: python增量计算
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    扫码加入运维网微信交流群X

    扫码加入运维网微信交流群

    扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

    扫描微信二维码查看详情

    客服E-mail:kefu@iyunv.com 客服QQ:1061981298


    QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


    提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


    本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



    合作伙伴: 青云cloud

    快速回复 返回顶部 返回列表