Python simple implementation of socket message sending and listening function example
- 2020-06-23 00:47:21
- OfStack
This article illustrates Python's simple implementation of socket message sending and listening function. To share for your reference, specific as follows:
Recently, I have been studying boost C++ library, which is used to handle large-scale and high-concurrency TCP connection data response in my work. If I want to test, I can also use boost::asio library to write, but it is not good for the flexible modification of the test code.
So I studied how to do python 1. Although the code samples given on the Internet are very basic and easy to understand, for people with zero knowledge of python, they can be a little more complicated. With some comments, they can master more basic grammar knowledge of socket and python.
Therefore, the sample codes of socket server and client of python are modified as follows according to my usage needs:
server end (single threaded)
# -*- coding: cp936 -*-
'''''
To establish 1 a python server , listen on the specified port,
If the port is accessed by a remote connection, get the remote connection and then receive the data,
And give feedback accordingly.
'''
if __name__=="__main__":
import socket
print "Server is starting"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8001)) # configuration soket , the binding IP Address and port number
sock.listen(5) # Sets the maximum number of allowed connections, each connection and server Communication compliance FIFO The principle of
print "Server is listenting port 8001, with max connection 5"
while True: # Cyclic polling socket Status, waiting for access
connection,address = sock.accept()
try:
connection.settimeout(50)
# To obtain 1 The loop starts processing the message sent by the connection
'''''
if server To process multiple connections simultaneously, the following block of statements should be multithreaded,
Otherwise, server It's always down here while Statement block is regulated 1 The number of connections occupied,
Unable to scan for other new connections, but multithreading affects code structure, so remember when the number of connections is greater than 1 when
The following statement should be changed to multithreading.
'''
while True:
buf = connection.recv(1024)
print "Get value " +buf
if buf == '1':
print "send welcome"
connection.send('welcome to server!')
elif buf!='0':
connection.send('please go out!')
print "send refuse"
else:
print "close"
break # Exit the connection listening loop
except socket.timeout: # If, after establishing a connection, the connection receives no data for the set time time out
print 'time out'
print "closing one connection" # when 1 After the loop exits, the connection can be closed
connection.close()
The client terminal sends different data to server in turn every 3 seconds:
if __name__=="__main__":
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8001))
import time
flag = '1'
while True:
time.sleep(3)
print 'send to server with value: '+ flag
sock.send(flag)
print sock.recv(1024)
flag = (flag=='1') and '2' or '1' #change to another type of value each time
sock.close()
After executing the above two pieces of code, you get the following result:
First execute ES35en.ES36en:
C:\Users\YanBo>D:\server.py
Server is starting
Server is listenting port 8001, with max connection 5
After client is executed:
C:\Users\YanBo>D:\client.py
send to server with value: 1
welcome to server!
send to server with value: 2
please go out!
send to server with value: 1
welcome to server!
send to server with value: 2
please go out!
.....
The corresponding output of server:
Get value 1
send welcome
Get value 2
send refuse
.....
If under linux, use
$ lsof -i:8001
You can list the server and client processes in progress, as they occupy port 8001
yanbo@yanbo-linux64-01:~$ lsof -i:8001
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python 2413 yanbo 3u IPv4 12907 0t0 TCP localhost:8001 (LISTEN)
python 2413 yanbo 4u IPv4 12910 0t0 TCP localhost:8001->localhost:38609 (ESTABLISHED)
python 2469 yanbo 3u IPv4 12222 0t0 TCP localhost:38609->localhost:8001 (ESTABLISHED)
As you can see, process 2413 is server.py 2469 is client.py
More information about Python can be found in the following topics: Summary of Python Socket Programming Skills, Python Data Structure and Algorithm Tutorial, Python Function Using Skills Summary, Python String Manipulation Skills Summary, Python Introduction and Advanced Classic Tutorial and Python File and Directory Manipulation Skills Summary
I hope this article is helpful for Python programming.