UDP鏈接:python
無鏈接,從一個端向另外一端發送獨立的數據分組服務器
使用UDP鏈接的客戶-服務器程序:socket
UDPServer.pycode
import socket serverPort = 50009 serverSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) serverSocket.bind(('',serverPort)) print("The server is ready to receive") while 1: message,clientAddress = serverSocket.recvfrom(2048) modifiedMessage = message.upper() serverSocket.sendto(modifiedMessage,clientAddress)
UDPClient.pyserver
import socket ServerName = '127.0.0.1' ServerPort = 50009 clientSocket =socket.socket(socket.AF_INET,socket.SOCK_DGRAM) message = input('Input your lowercase sentence:') clientSocket.sendto(message.encode(),(ServerName,ServerPort)) modifiedmessage,serverAddress = clientSocket.recvfrom(2048) print (modifiedmessage.decode()) clientSocket.close
注意:blog
clientSocket =socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 接口
AF_INET:Address Family爲inet表示IPV4格式(AF_INET6表示IPV6)進程
SOCK_DGRAM:表示基數據報格式,表示UDP鏈接input
sendto:發送未創建鏈接的UDP數據包,這裏是爲報文附上目的地址,並向進程的套接字發送結果分組class
recvfrom:用於從(已鏈接)套接口上接收數據,並捕獲數據發送源的地址()
須要先執行服務器端代碼,而後再執行客戶端,執行結果以下: