自己动手用UDP实现简单的用户-服务器程序,基于Python3实现
客户端
代码如下:
"""
UDP Socket的客户端
环境 python3
"""
from socket import *
serverName = '180.201.20.208'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
# python3 改动
message = input("Input lowercase sentence:")
# python3 改动 socket要求byte类型数据
clientSocket.sendto(message.encode(), (serverName, serverPort))
modifiedMessage ,serverAddress = clientSocket.recvfrom(2048)
# python3 改动
print(modifiedMessage)
clientSocket.close()
服务器端
"""
UDP Socket的服务器端
环境 python3
"""
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(("", serverPort))
# python3 改动
print("The server is ready to receive")
while True:
message, clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.upper()
serverSocket.sendto(modifiedMessage, clientAddress)
注意:服务器端要开启12000端口号,使用ufw allow 12000
同时开启UDP和TCP端口号
实验结果
发送一个”abbb”小写字母,能够返回大写字母
证明一个最简单的CS小程序已经成功