程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python uses sockets to transmit data (UDP) from different computers in the same LAN

編輯:Python

        This use udp Protocol transfer data ( That is, set word selection udp The corresponding parameter )

One 、 In front of Conditions :

          Import socket package , Two computers under one LAN ( Or create one locally win virtual machine )

Two 、 send data

        1、 Create suite word

        2、 send data

        3、 Close the kit word

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()

3、 ... and 、 receive data

        1、 Create suite word

        2、 Bind local information (ip And port port)

        3、 receive data

        4、 Close the kit word

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 .

Four 、 Be careful !!:

        recvfrom When there is no link or data received, it will cause function congestion !! Be similar to input, It's just input Waiting for you to enter data on the command line , and recvfrom It is waiting for the link and data of the client or server .

        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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved