


This article brings you an introduction to UDP communication through sockets in python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
UDP
TCP establishes a reliable connection, and both communicating parties can send data in the form of streams. Compared with TCP, UDP is a connectionless protocol. When using the UDP protocol, there is no need to establish a connection. You only need to know the IP address and port number of the other party to send data packets directly. But I don't know if it can be reached.
Let’s take a look at how to transmit data through the UDP protocol. Similar to TCP, the communication parties using UDP are also divided into
client and server
Socket structure diagram to implement UDP communication
UDP server
Similar to TCP, the communication parties using UDP are also divided into clients and servers. The server first needs to bind the port. But there is no need to monitor the client's connection
#server import socket #创建Socket时, SOCK_DGRAM 指定了这个Socket的类型是UDP。 server = socket.socket(type=socket.SOCK_DGRAM) server.bind(('192.168.1.165',7890)) #不需要调用 listen() 方法, 而是直接接收来自任何客户端的数据 print('服务端已开启7890端口,正在等待被连接...') #recvfrom() 方法返回数据和客户端的地址与端口, 这样, 服务器收到数据后, #直接调用 sendto() 就可以把数据用UDP发给客户端 data,address = server.recvfrom(1024) print("client>>",data.decode('utf-8')) print("客户端连接的socket地址:", address) server.sendto(b'drink more water!',address) server.close()
UDP client
When the client uses UDP, first still create a UDP-based Socket, and then, there is no need to call connect( ), directly send data to the server through sendto()
import socket #创建Socket时, SOCK_DGRAM 指定了这个Socket的类型是UDP。 client = socket.socket(type=socket.SOCK_DGRAM) send_data =b'hello sheenstar' client.sendto(send_data,('192.168.1.165',7890)) re_Data,address = client.recvfrom(1024) print('server>>',re_Data.decode('utf-8')) client.close()
Test results
Use two command lines to start the server and client tests respectively
Open the server
Complete a UDP communication
The above is the detailed content of Introduction to socket UDP communication in python (with examples). For more information, please follow other related articles on the PHP Chinese website!

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Notepad++7.3.1
Easy-to-use and free code editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
