Basic Python socket programming
Basic Python socket programming
This article describes the basic Python socket programming tutorials, including the basic sending and receiving information. For more information, see
This article describes how to use Python for Socket network programming. If you already have basic network programming knowledge and basic Python syntax knowledge, the code in this article runs under Python 3.4 if it is not described.
The socket function of Python is encapsulated in the socket library. To use socket, remember to import socket first. For details about the socket library, see the official documentation.
Create Socket
First, create a socket and use the socket function in the socket library.
?
?
1 2 |
# Create an INET, STREAM socket S = socket. socket (socket. AF_INET, socket. SOCK_STREAM) |
In this example, a TCP socket is created. The default values of the first two parameters of the socket. socket function are socket. AF_INET and socket. SOCK_STREAM. When creating a TCP socket, you can directly write it as socket. socket ().
Connect to the server
Use the socket connect function to connect to the server. The following parameters are valid.
?
1 2 3 |
S. connect ("localhost", 8000 )) S. connect ('2017. 0.0.1 ', 127 )) S. connect ('www .baidu.com ', 80 )) |
Send data
There are two methods to send data: send and sendall. send cannot ensure that all data is sent completely. It returns the length of the sent data, the program sends data cyclically until all data has been sent.
?
1 2 3 4 5 6 7 8 |
Def mysend (s, msg ): Total_len = len (msg) Total_sent = 0 While total_sent <total_len: Sent = s. send (msg [total_sent:]) If sent = 0: Raise RuntimeError ("socket connection broken ") Total_sent + = sent |
Sendall ensures that all data has been sent. Unless an error occurs during the sending process, sendall actually sends data cyclically until all data is sent completely.
Here we also want to talk about a special point, starting with an example:
?
1 2 3 4 |
Import socket S = socket. socket () S. connect ('www .baidu.com ', 80 )) S. sendall ('test ') |
All of the things mentioned above are nothing special. Execute the above Code in Python 2 and Python 3 respectively, and the result is:
?
1 2 3 4 5 |
# Python 2.7 >>> Import socket >>> S = socket. socket () >>> S. connect ('www .baidu.com ', 80 )) >>> S. sendall ('test ') |
Python 2 is successfully executed.
?
1 2 3 4 5 6 7 8 |
# Python 3.4 >>> Import socket >>> S = socket. socket () >>> S. connect ('www .baidu.com ', 80 )) >>> S. sendall ('test ') Traceback (most recent call last ): File "<stdin>", line 1, in <module> TypeError: 'str' does not support the buffer interface |
An exception occurred in Python 3.
I couldn't execute the same code in another environment. I didn't make a mistake, so I was so angry with my computer. Well, you did not make a mistake. It is because the environment has changed and the result has changed. Please go to the official instructions.
Receive data
Use the recv function to receive data:
?
In Python 3, a bytes object is returned, and in Python 2, a string is returned. Note that the length of data returned by the function is smaller than or equal to the length specified by the parameter. To receive data of the specified length, you need to receive data cyclically.
?
1 2 3 4 5 6 7 8 9 10 |
Def myreceive (s, msglen ): Chunks = [] Bytes_recd = 0 While bytes_recd <msglen: Chunk = s. recv (min (msglen-bytes_recd, 2048 )) If chunk = B '': Raise RuntimeError ("socket connection broken ") Chunks. append (chunk) Bytes_recd = bytes_recd + len (chunk) Return B ''. join (chunks) |
Close connection
When the connection is no longer needed, you can use close to close the socket connection. After the connection is closed, no operation can be performed. When a socket is recycled, it is automatically closed, but do not rely on this mechanism. When the socket is not required, it is automatically closed.
Server
Steps for executing the server program:
1. Create a server socket
1. Bind the server socket to the specified address and port
1. Listen for connection
1. Accept Client Connection
1. Process client data
1. disable Client Connection
A simple echo server example:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Import socket HOST ='' PORT = 10022 S = socket. socket (socket. AF_INET, socket. SOCK_STREAM) S. bind (HOST, PORT )) S. listen (10) Conn, addr = s. accept () While True: Data = conn. recv (1024) If not data: Break Conn. sendall (data) Conn. close () |
Client Program:
?
1 2 3 4 5 6 7 8 9 10 11 |
Import socket HOST = 'localhost' PORT = 10022 S = socket. socket (socket. AF_INET, socket. SOCK_STREAM) S. connect (HOST, PORT )) S. sendall (B 'hello socket ') Data = s. recv (1024) Print ('received', repr (data )) S. close () |
Error Handling
When an error occurs during socket processing, an exception is thrown. socket-related exceptions include:
-Socket. error
-Socket. herror
-Socket. gaierror
-Socket. timeout
?
1 2 3 4 5 6 7 8 9 10 11 |
Import socket HOST = None PORT = 10022 Try: S = socket. socket (socket. AF_INET, socket. SOCK_STREAM) S. bind (HOST, PORT )) S. listen (10) Failed T: socket. error as msg: Print (msg) |