This article describes the use of Python for socket network programming, assuming that the reader has the basic knowledge of network programming and Python basic syntax knowledge, the code in this article, if not stated, is run under Python 3.4.
Python socket functions are encapsulated in the socket library, to use the socket, remember to import the Socket,socket library detailed introduction See official documentation.
Create a socket
First create a socket and use the socket function in the socket library to create it.
# Create an INET, STREAM socket
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
The default values for the first two parameters of a TCP Socket,socket.socket function created in the example are Socket.af_inet and Socket.sock_stream, which can be written directly as Socket.socket when the TCP socket is created ( )。
connecting to a server
Using the Connect function of the socket is connected to the server, several of the following parameters are valid.
S.connect ((' localhost ', 8000)) S.connect ((' 127.0.0.1 ',
8000))
s.connect ((' www.baidu.com ', 80))
Send data
Send data two methods send and sendall,send do not guarantee that all the data is sent, it returns the length of the sent data, and the program loops through the data until all the data is sent.
def mysend (S, msg):
Total_len = Len (msg)
total_sent = 0 while
total_sent < total_len:
sent = S.send (ms G[total_sent:])
if sent = = 0:
raise RuntimeError ("Socket Connection broken")
total_sent + = Sent
Sendall can guarantee that all the data has been sent, unless there is an error in the sending process, it is actually looping through the data until all the data is sent.
Here's another place to take a special look, starting with an example:
Import socket
s = socket.socket ()
s.connect (' www.baidu.com ', #)
s.sendall (' test ')
It's all the stuff that's been said, nothing special, execute the code in Python 2 and Python 3, and the result is:
# Python 2.7
>>> import socket
>>> s = socket.socket ()
>>> s.connect (' Www.baidu.com ',)
>>> s.sendall (' test ')
Execution succeeded in Python 2.
# Python 3.4
>>> Import socket
>>> s = socket.socket ()
>>> s.connect (' Www.baidu.com ',)
>>> 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.
The same code to change the environment can not be implemented, I did not write wrong Ah, angry smashed the computer. Well, you did not write wrong, the environment has changed, leading to changes in the results of the official note.
Receive data
To receive data using the RECV function:
The bytes object is returned in Python 3, and string is returned in Python 2. Note The data length returned by the function is less than or equal to the length specified by the parameter, and you need to iterate over the data to receive the specified length of data.
def myreceive (S, msglen):
chunks = []
BYTES_RECD = 0 while
Bytes_recd < msglen:
chunk = s.recv (min (msg LEN-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
You can use close to turn off the socket connection when the connection is no longer needed, and no further action will be allowed after the closed connection. When a socket is reclaimed, it is automatically closed, but do not rely on this mechanism and actively close when you do not need a socket.
Service side
Steps for server-side program execution:
1. Create a service port socket
1. Bind the server socket to the specified address and port
1. Listening connection
1. Accept client Connections
1. Processing the data of the client
1. Close client connections
A simple example of ECHO server:
Import socket
HOST = '
PORT = 10022
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
S.bind ((HOST, PORT)
S.listen
conn, addr = S.accept () while
True:
data = CONN.RECV (1024)
if not data:
break
conn.sendall (data)
Conn.close ()
Client program:
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
Errors during socket processing throw exceptions, and socket-related exceptions are:
- -Socket.error
- -Socket.herror
- -Socket.gaierror
- -Socket.timeout
Import socket
HOST = None
PORT = 10022
try:
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
S.bind ((HOST, PORT)
s.listen
except:socket.error as msg:
print (msg)