一、客户机
打开cmd使用ipconfig指令查询自己电脑的ip地址
serverName = 本机ip地址
注意,报文在UDP中传输是bytes类型,因此需要将输入的字符串编码成bytes型(encode)
读出服务器处理完成的报文,再解码(decode)为字符串
from socket import * serverName = "192.128.3.204" serverPort = 12000 clientSocket = socket(AF_INET,SOCK_DGRAM) message = input("Input lowercase sentence:") message = message.encode() clientSocket.sendto(message, (serverName, serverPort)) modifiedMessage,serverAddress = clientSocket.recvfrom(2048) modifiedMessage = modifiedMessage.decode() print(modifiedMessage) print(serverAddress) 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.upper() serverSocket.sendto(modifiedMessage,clientAddress)
三、同时运行两个代码文件
原文地址:https://www.cnblogs.com/cnlntr/p/12585140.html
时间: 2024-10-05 14:36:05