实现功能
1.客户端从键盘读取一行字符(数据)并将数据发送到服务器
2.服务器接收到该数据并将这些字符转换为大写
3.服务器将修改的数据发送给客户端
4.客户端接收到修改的数据并在其监视器上将该行显示出来
测试环境说明
ubuntu16.04 虚拟机
服务器客户通讯流程
客户端例子程序
from socket import *
serverAddress = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET,SOCK_DGRAM)
message = raw_input('Input lowercase sentence:')
clientSocket.sendto(message.encode(),(serverAddress,serverPort))
modifiedMessage,serverAddress = clientSocket.recvfrom(2048)
print(modifiedMessage.decode())
clientSocket.close()
服务器代码
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_DGRAM)
serverSocket.bind(('',serverPort))
print('The server is ready to receive')
while True:
message,clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.decode().upper()
serverSocket.sendto(modifiedMessage.encode(),clientAddress)
测试结果
启动Server
root@virtual-machine:/home/test/python# python UDPServer.py
The server is ready to receive
启动Client
root@virtual-machine:/home/test/python# python UDPClient.py
Input lowercase sentence:adbcde3
ADBCDE3