This use udp Protocol transfer data ( That is, set word selection udp The corresponding parameter )
Import socket package , Two computers under one LAN ( Or create one locally win virtual machine )
import socket
def main():
# Create a udp Kit word
udp_socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# Send and receive data using kit words
send_data=input(' Please enter the data you want to send :')
# The goal is IP And port , A tuple type
ip_adders=('192.168.25.134',7788)
udp_socket.sendto(send_data.encode('utf-8'),ip_adders)
# Close the kit word
udp_socket.close()
if __name__ == '__main__':
main()
import socket
def main():
# Create a udp Kit word
udp_socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# Bind local related information , If you don't bind , Then the system will randomly assign , Must be bound to the computer ip and port
local_addr =('' ,7788) # The first parameter of tuple is native IP, Can be an empty string , Will automatically generate the local IP
udp_socket.bind(local_addr)
# Waiting for the receiver to send data
#rs Stored in is a tuple ( Received data ,( The sender's ip,port))
rs_data=udp_socket.recvfrom(1024)
rs_masg =rs_data[0]
rs_addr =rs_data[1]
print(rs_data)
# Received data decoding display
print(rs_masg.decode('utf-8'))
print(rs_addr)
# Close the kit word
udp_socket.close()
if __name__ == '__main__':
main()
Received data :( Received data ,( The sender's ip,port))
The above is a single send and receive data , Want to send and receive data all the time , Put the sending and receiving data codes into while True In the loop .
Of course, you can also send it to yourself on a computer , ha-ha . Just put the goal IP How to change the cost machine IP The address will do .
It can be done through code :server_socket.setblocking(False) Set socket to non blocking mode , But when it is set to non blocking mode ,recv No data received , Would throw exceptions , You can add exception handling by yourself