1. 程式人生 > >Python實現udp協議的簡單伺服器和客戶端通訊

Python實現udp協議的簡單伺服器和客戶端通訊

簡單socket程式在兩臺電腦之間傳輸訊息,分為客戶端和服務端,分別在兩臺電腦上執行後即可進行簡單的訊息傳輸,也可以在一臺電腦上測試,設定兩個不同的埠即可
以下是程式碼在一臺電腦上執行,開兩個終端即可.
伺服器端:

import socket
byte = 1024
#兩個埠要保持一致
port = 25535  
host = ""
addr = (host, port)

#建立套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#繫結
sock.bind(addr)
print("waiting to receive messages..."
) while True: (data, addr) = sock.recvfrom(byte) text = data.decode('utf-8') if text == 'exit': break else : print('The client at {} says {!r}'.format(addr, text)) text = 'Your data was {}bytes long'.format(len(data)) data = text.encode('utf-8') sock.sendto(data, addr) #關閉套接字
sock.close()

客戶端:

import socket

host = '127.0.0.1'    
#兩個段口必須一致
port = 25535
addr = (host, port)
byte = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
    data = input('Please input the message: ')
    text = data.encode('utf-8')
    sock.sendto(text, addr)

    #輸入'exit'退出
if data == 'exit': break else: #getsockname返回當前套接字的資訊(IP,埠號) print("The OS assigned me the address {}".format(sock.getsockname())) data, addr = sock.recvfrom(byte) text = data.decode("utf-8") print('The server {} replied{!r}'.format(addr, text)) sock.close()