客户端(需要预先知道服务端地址,IP地址和端口号)
from socket import *
servername = 'hostname/ip address' //服务器IP地址或者主机名
serverPort = 12000 //服务器端口号
clientSocket = socket(AF_INET, SOCK_DGRAM) //创建socket
message = input('Input lowercase sentence:') //输入小写字符串
message = str.encode(message) //str转成byte
clientSocket.sendto(message, (servername, serverPort)) //message发送至服务器,同时会自动发送客户端IP和端口号给服务器
modifiedMessage, serverAddress = clientSocket.recvfrom(2048) //接收服务器回送的message
print (modifiedMessage)
clientSocket.close() //关闭socket
服务端
from socket import *
serverPort = 12000 //服务器端口号12000
serverSocket = socket(AF_INET, SOCK_DGRAM) //创建socket,两个参数代表ipv4和UDP
serverSocket.bind(('', serverPort)) //将socket与端口号12000绑定
print ('The server is ready to receive')
while True:
message, clientAddress = serverSocket.recvfrom(2048) //等待接收客户端的消息,2048为缓存大小
modifiedMessage = message.upper() //将接收到的转成大写
serverSocket.sendto(modifiedMessage, clientAddress) //回送消息至客户端,客户端地址由ip地址和端口号组成
print('received')