欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python啟動(dòng)UDP服務(wù),監(jiān)聽并接收客戶端數(shù)據(jù)方式

 更新時(shí)間:2024年07月19日 16:20:16   作者:Lightning-py  
這篇文章主要介紹了Python啟動(dòng)UDP服務(wù),監(jiān)聽并接收客戶端數(shù)據(jù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

Python啟動(dòng)UDP服務(wù),監(jiān)聽并接收客戶端數(shù)據(jù)

可以使用Python的socket庫實(shí)現(xiàn)UDP協(xié)議的驗(yàn)證,以下是一個(gè)簡(jiǎn)單的示例代碼:

服務(wù)器

[root@localhost python]# cat udp_server.py 
import socket

# 創(chuàng)建一個(gè)UDP socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 綁定到本地 IP 和端口
local_addr = ('192.168.6.211', 8888)
udp_socket.bind(local_addr)

print('UDP server is listening...')

while True:
    # 接收數(shù)據(jù)
    data, addr = udp_socket.recvfrom(1024)
    print(f'Received data from {addr}: {data.decode()}')

    # 回復(fù)數(shù)據(jù)
    reply = 'Received: ' + data.decode()
    udp_socket.sendto(reply.encode(), addr)

[root@localhost python]#

客戶端

[root@localhost python]# cat udp_server.py 
import socket

# 創(chuàng)建一個(gè)UDP socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 發(fā)送數(shù)據(jù)
remote_addr = ('192.168.6.211', 8888)
udp_socket.sendto('Hello, UDP!'.encode(), remote_addr)

# 接收數(shù)據(jù)
data, addr = udp_socket.recvfrom(1024)
print(f'Received data from {addr}: {data.decode()}')

# 關(guān)閉 socket
udp_socket.close()

[root@localhost python]#

以上代碼創(chuàng)建了一個(gè)UDP socket,并綁定到本地的IP和端口8888。

接著使用recvfrom()方法接收數(shù)據(jù),并使用sendto()方法發(fā)送數(shù)據(jù)。最后,關(guān)閉socket。

可以使用兩個(gè)終端分別運(yùn)行該程序,并觀察數(shù)據(jù)的傳輸情況,從而驗(yàn)證UDP協(xié)議的可靠性。

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論