UDP连接:
无连接,从一个端向另一端发送独立的数据分组
使用UDP连接的客户-服务器程序:
UDPServer.py
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.py
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
注意:
clientSocket =socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
AF_INET:Address Family为inet表示IPV4格式(AF_INET6表示IPV6)
SOCK_DGRAM:表示基数据报格式,表示UDP连接
sendto:发送未建立连接的UDP数据包,这里是为报文附上目的地址,并向进程的套接字发送结果分组
recvfrom:用于从(已连接)套接口上接收数据,并捕获数据发送源的地址()
需要先执行服务器端代码,然后再执行客户端,执行结果如下: