current position：Home>Python Network Programming -- create a simple UPD socket to realize mutual communication between two processes
Python Network Programming -- create a simple UPD socket to realize mutual communication between two processes
2022-01-30 04:42:34 【Alvin305】
Little knowledge , Great challenge ！ This article is participating in “ A programmer must have a little knowledge ” Creative activities
What is? socket
Socket Usually also known as “ Socket ”, Applications usually go through “ Socket ” Realize sending a request to the network or corresponding network request , So as to realize the mutual communication between different computers or different processes of the same computer
stay python in , adopt socket() Function to create a socket , The syntax is as follows ：
family： Socket family , Generally divided into AF_UNIX and AF_INET, General situation AF_INET Use more
type： Socket type , Generally divided into SOCK_STREAM and SOCK_DGRAM, If it is based on TCP The socket of the protocol uses SOCK_STREAM, If the creation is based on UDP The socket of is SOCK_DGARM
proto： The default is 0
Socket Built-in functions
socket There are a lot of built-in functions , Here are just a few functions we will use
bind()： Bind address to socket , Parameters are tuple types ,（ip,port）
sendto()： Used for sending UPD data , Send data to socket ,address In the form of （ipaddr,port） Tuple form of , Specify the address to receive information , The return value is the number of bytes sent
recvform()： Used to receive UPD data , The return value is a tuple containing data and sending address (data,address)
close()： Close socket , Be sure to close the socket after sending and receiving data
Create two files, one for sending data sender.py And a for receiving data receiver.py. The code is as follows ：
# sender.py from socket import * udp= socket(AF_INET,SOCK_DGRAM) udp.bind(('',7788))# binding IP And port ,IP If it is empty, it indicates that it is local , port 7788 data = input(" Please enter what you want to send ：") upd.sendto(data.encode('utf-8'),('10.34.2.92',7789))# Data to send , And the address where the data is received , The content needs to be encoded , To prevent the occurrence of random code udp.close()# Close socket Copy code
#receiver.py from socket import * udp = socket(AF_INET,SOCK_DGRAM) udp.bind(('',7789)) print(" Waiting to receive message ") content ,addr = udp.recvfrom(1024) print(" The news comes from ：【%s:%s】" % (addr,addr)) print(content.decode('utf-8'))# Need to decode , To prevent the occurrence of random code udp.close()# Close socket Copy code
Open two command-line windows and switch to the directory where the two files are located ,
One of the inputs ：python sender.py enter , At this time, you will be prompted to enter the content to be sent , You can enter some data at will
Another input ：python receiver.py enter , Then you will receive a message from sender.py Data sent .
author[Alvin305],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Getting started with Python - object oriented - special methods
- Using linear systems in python with scipy.linalg
- Fast power modulus Python implementation of large numbers
- Python architects recommend the book "Python programmer's Guide" which must be read by self-study Python architects. You are welcome to take it away
- Decoding the verification code of Taobao slider with Python + selenium, the road of information security
- Python game development, pyGame module, python implementation of skiing games
- Python collects and monitors system data -- psutil
- Python + selenium automated test: page object mode
- You can easily get started with Excel. Python data analysis package pandas (IV): any grouping score bar
- Python ThreadPoolExecutor restrictions_ work_ Queue size
guess what you like
Python generates and deploys verification codes with one click (Django)
[Python kaggle] pandas basic exercises in machine learning series (6)
Using linear systems in python with scipy.linalg
Using Python to realize national second-hand housing data capture + map display
How to make Python run faster? Six tips!
Python chat room (Tkinter writing interface, streaming, socket to realize private chat, group chat, check chat records, Mysql to store data)
This pandas exercise must be successfully won
[algorithm learning] sword finger offer 64 Find 1 + 2 +... + n (Java / C / C + + / Python / go / trust)
Understand Python's built-in function and add a print function yourself
Python implements JS encryption algorithm in thousands of music websites
- leetcode 35. Search Insert Position（python）
- [introduction to Python visualization]: 12 small examples of complete data visualization, taking you to play with visualization ~
- Learning this Python library can reduce at least 100 lines of code
- leetcode 67. Add Binary（python）
- Regular re parameter replacement of Python 3 interface automation test framework
- V. pandas based on Python
- Only 15 lines of code is needed for face detection! (using Python and openCV)
- [Python crawler Sao operation] you can crawl Sirius cinema movies without paying
- leetcode 69. Sqrt(x)（python）
- Teach you to read the source code of Cpython (I)
- Snowball learning started in the fourth quarter of Python. One needs three meals. I have a new understanding of Python functional programming, process-oriented, object-oriented and functional
- leetcode 88. Merge Sorted Array（python）
- Don't you know more about a python library before the end of 2021?
- Python crawler web page parsing artifact XPath quick start teaching!!!
- Use Python and OpenCV to watermark the image
- String and related methods of Python data type introduction
- Heapq module of Python module
- Introduction to beautiful soup of Python crawler weapon, detailed explanation, actual combat summary!!!
- Event loop of Python collaboration series
- Django docking pin login system
- [recalling the 1970s] using Python to repair the wonderful memories of parents' generation, black-and-white photos become color photos
- You used to know Python advanced
- Pyinstaller package Python project
- 2021 IEEE programming language rankings: Python tops the list!
- Implementation of Python automatic test control
- Python advanced: [Baidu translation reverse] graphic and video teaching!!!
- Do you know the fuzzy semantics in Python syntax?
- [Python from introduction to mastery] (XXVII) learn more about pilot!
- Playing excel office automation with Python
- Some applications of heapq module of Python module
- Python and go languages are so popular, which is more suitable for you?
- Python practical skills task segmentation
- Python simulated Login, numpy module, python simulated epidemic spread
- Python opencv contour discovery function based on image edge extraction
- Application of Hoff circle detection in Python opencv
- Python reptile test ox knife (I)
- Day 1: learn the Django framework of Python development
- django -- minio_ S3 file storage service
- [algorithm learning] 02.03 Delete intermediate nodes (Java / C / C + + / Python / go)
- Learning in Python + opencv -- extracting corners