计算机网络-利用Socket进行网络通信
以下的通信无论是利用 UDP Socket 还是 TCP Socket 都是从客户端获取一串字符串,然后在服务端全部转为大写,之后返回客户端。
TCP Client
from socket import *
server_name = "10.27.138.11"
server_port = 12000
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect((server_name, server_port))
sentence = input("input lowercase sentence:")
client_socket.send(sentence.encode())
modified_sentence = client_socket.recv(1024)
print(modified_sentence.decode())
client_socket.close()
UDP Client
from socket import *
server_name = "10.27.138.11"
server_port = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
while True:
message = input('Input lowercase sentence:')
if message == "leeson":
break
clientSocket.sendto(message.encode(), (server_name, server_port))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print(modifiedMessage.decode())
clientSocket.close()