Home > Backend Development > Python Tutorial > Introduction to python socket programming

Introduction to python socket programming

高洛峰
Release: 2016-10-18 11:14:35
Original
1069 people have browsed it

Steps to write server in python:

1. The first step is to create a socket object. Call the socket constructor. For example:

socket = socket.socket( family, type )

family parameter represents the address family, which can be AF_INET or AF_UNIX. The AF_INET family includes Internet addresses, and the AF_UNIX family is used for inter-process communication on the same machine. The

type parameter represents the socket type, which can be SOCK_STREAM (stream socket) and SOCK_DGRAM (datagram socket).

2. The second step is to bind the socket to the specified address. This is achieved through the bind method of the socket object:

socket.bind(address)

For the socket created by AF_INET, the address address must be a two-element tuple in the format (host, port). host represents the host and port represents the port number. If the port number is in use, the host name is incorrect, or the port has been reserved, the bind method will raise a socket.error exception.

3. The third step is to use the listen method of the socket socket to receive the connection request.

socket.listen( backlog )

backlog specifies the maximum number of clients allowed to connect to the server. Its value is at least 1. After receiving connection requests, these requests need to be queued. If the queue is full, the request is rejected.

4. The fourth step is that the server socket waits for the client to request a connection through the socket's accept method.

connection, address = socket.accept()

When the accept method is called, the socket will enter the "waiting" state. When the client requests a connection, the method establishes the connection and returns to the server. The accept method returns a tuple containing two elements (connection, address). The first element, connection, is the new socket object through which the server must communicate with the client; the second element, address, is the client's Internet address.

5. The fifth step is the processing stage. The server and client communicate (transmit data) through the send and recv methods. The server calls send and sends information to the client in the form of a string. The send method returns the number of characters sent. The server receives information from the client using the recv method. When calling recv, the server must specify an integer that corresponds to the maximum amount of data that can be received with this method call. The recv method will enter the "blocked" state when receiving data, and finally return a string to represent the received data. If the amount of data sent exceeds recv, the data will be truncated. Excess data will be buffered at the receiving end. On subsequent calls to recv, excess data is removed from the buffer (along with any other data the client may have sent since the last call to recv).

6. After the transmission is completed, the server calls the close method of the socket to close the connection.

Steps to write client in python:

1. Create a socket to connect to the server: socket = socket.socket(family, type)

2. Use the connect method of the socket to connect to the server. For the AF_INET family, the connection format is as follows:

socket.connect( (host, port) )

host represents the server host name or IP, and port represents the port number bound to the server process. If the connection is successful, the client can communicate with the server through the socket. If the connection fails, a socket.error exception will be raised.

3. In the processing stage, the client and server will communicate through the send method and recv method.

4. When the transmission is completed, the client closes the connection by calling the close method of the socket.

Here is a simple example:

server.py

if __name__ == '__main__':
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 8001))
    sock.listen(5)
    while True:
        connection,address = sock.accept()
        try:
            connection.settimeout(5)
            buf = connection.recv(1024)
            if buf == '1':
                connection.send('welcome to server!')
            else:
                connection.send('please go out!')
        except socket.timeout:
            print 'time out'
        connection.close()
Copy after login

client.py

if __name__ == '__main__':
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('localhost', 8001))
    import time
    time.sleep(2)
    sock.send('1')
    print sock.recv(1024)
    sock.close()
Copy after login

Run server.py in the terminal, and then run client.py, "welcome to server!" will be printed in the terminal. If you change sock.send('1') of client.py to another value, "please go out!" will be printed on the terminal. If you change time.sleep(2) to a value greater than 5, the server will time out.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template