2017.07.08 Python network programming setting and getting the default socket timeout

1. Set and get the default socket timeout time:

# -*- coding: UTF-8 -*-<br># Sometimes you need to deal with the default value of some properties of the socket library, such as socket timeout<br># !usr/bin/env python<br>#Python Network Programming Cookbook --Chapter-1<br># This program is optimized for Python 2.7<br># It may run on any other version with/without modifications<br><br>import socket<br><br>def test_socket_timeout():<br>    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)<br>    print "The default socket timeout is: %s" %s.gettimeout()<br>    s.settimeout(100)<br>    print "The current socket timeout is: %s" %s.gettimeout()<br><br>if __name__=='__main__':<br>    test_socket_timeout()<br><br>

There is a problem running the program: No py.test runner found in selected interpreter

Solution: Did not find the py.test file, give the pycharm software administrator permission to run, then install the pytest package, pip install pytest

The result is as follows:

2. Handle socket errors gracefully:

# -*- coding: UTF-8 -*-<br># Write several try-except code blocks, each code block corresponds to a possible error<br># !usr/bin/env python<br>#Python Network Programming Cookbook --Chapter-1<br># This program is optimized for Python 2.7<br># It may run on any other version with/without modifications<br><br><br>import socket<br>import sys<br>import argparse<br><br>def main( ):<br>    parser=argparse.ArgumentParser(description='socket Error Example')<br>    parser.add_argument('--host',action="store",dest="host",required=False)<br>    parser.add_argument('--port',action="store",dest="port",type=int,required=False)<br><br>    parser.add_argument('--file',action="store",dest="file",required=False)<br>    given_args = parser. parse_args()<br>    host=given_args.host<br>    port=given_args.port<br>    filename=given_args.file<br><br>    try:<br>        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)<br>    except socket.error, e:<br>        print "An error occurred while creating the sock object: %s" %e<br>        sys. exit(1)<br><br><br>    try:<br>        print host, port<br>        s. connect((host,port))<br>    except socket.gaierror, e:<br>        print "An error occurred in address release when connecting to the server: %s" %e<br>        sys. exit(1)<br>    except socket.error, e:<br>        print "Connection error: %s" %e<br>        sys. exit(1)<br><br><br>    try:<br>        s.sendall("GET %s HTTP/1.0\r\\
\r\\
" %filename)<br>    except socket.error, e:<br>        print "An error occurred while sending data: %s" %e<br>        sys. exit(1)<br><br><br>    while 1:<br><br>        try:<br>            buf=s.recv(2048)<br>        except socket.error, e:<br>            print "Error in receiving data: %s" %e<br>            sys. exit(1)<br>        if not len(buf):<br>            break<br><br>        sys.stdout.write(buf)<br><br><br>if __name__=='__main__':<br>    main()

3. Modify the buffer size of socket sending and receiving:

# -*- coding: UTF-8 -*-<br># The default socket buffer size may not be enough, you can change the default socket buffer size to a more appropriate value<br># !usr/bin/env python<br>#Python Network Programming Cookbook --Chapter-1<br># This program is optimized for Python 2.7<br># It may run on any other version with/without modifications<br><br>import socket<br><br>SEND_BUF_SIZE=4096<br>RECV_BUF_SIZE=4096<br><br>def modify_buf_size():<br>    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)<br>    <br>    bufsize=sock.getsockopt(socket.SOL_SOCKET,socket.SO_SNDBUF)<br>    print "The previous size of the buffer: %d" %bufsize<br><br>    sock.setsockopt(socket.SOL_TCP,socket.TCP_NODELAY,1)<br>    sock. setsockopt(<br>        socket.SOL_SOCKET,<br>        socket. SO_SNDBUF,<br>        SEND_BUF_SIZE<br>    )<br>    sock. setsockopt(<br>        socket. SOL_SOCKET,<br>        socket.SO_RCVBUF,<br>        RECV_BUF_SIZE<br>    )<br><br>    bufsize=sock.getsockopt(socket.SOL_SOCKET,socket.SO_SNDBUF)<br>    print "The modified buffer size is: %d" %bufsize<br><br>if __name__=='__main__':<br>    modify_buf_size()

4. Change the socket to blocking or non-blocking mode: By default, TCP sockets are in blocking mode, that is, unless an operation is completed, control will not be returned to the program

For example: after calling the connect() API, the connection operation will prevent the program from continuing to execute until the connection is successful

In many cases, you don’t want the program to wait for the server to respond or have an abnormal termination operation

# -*- coding: UTF-8 -*-<br># In Python, sockets can be set to blocking or non-blocking mode,<br># In non-blocking mode, after calling the API, such as send() or recv() methods will throw an exception if they encounter problems,<br># But under the blocking model, encountering a problem does not block the operation<br># !usr/bin/env python<br>#Python Network Programming Cookbook --Chapter-1<br># This program is optimized for Python 2.7<br># It may run on any other version with/without modifications<br><br>import socket<br><br>def test_socket_modes():<br>    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)<br>    s. setblocking(1)<br>    s.settimeout(0.5)<br>    s.bind(("127.0.0.1",0))<br><br>    socket_address=s.getsockname()<br>    print "Server login socket:%s" %str(socket_address)<br><br>    while(1):<br>        s. listen(1)<br><br>if __name__=='__main__':<br>    test_socket_modes()<br><br>



The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledgePython entry skill treeBasic skillsNetwork programming 258778 people are studying systematically