一、简单实现:
客户端程序:
from socket import *
server_name = "192.168.1.4"
server_port = 12000
# 创建客户套接字
client_socket = socket(AF_INET, SOCK_STREAM)
# 客户向服务器发送TCP连接
client_socket.connect((server_name, server_port))
sentence = input('Input lowercase sentence:')
# 通过TCP连接,客户可以向服务器发送并接收字节
client_socket.send(sentence.encode())
modified_sentence = client_socket.recv(1024)
print('From Server: ', modified_sentence.decode())
# 关闭用户套接字,关闭TCP连接
client_socket.close()
服务端程序:
from socket import *
server_port = 12000
# 创建套接字
server_socket = socket(AF_INET, SOCK_STREAM)
# 将服务器的端口号和套接字关联起来
server_socket.bind(('', server_port))
# 让服务器聆听来自客户端的TCP请求,请求连接的最大数至少为1
# 如果server_socket被关闭,就无法接收新的客户端TCP请求
server_socket.listen(1)
print('The server is ready to receive.')
while True:
# 创建一个由该用户专用的新套接字,客户与服务器完成了握手
# TCP连接创建完成,客户与服务器现在可以通过该连接相互发送字节
connection_socket, addr = server_socket.accept()
sentence = connection_socket.recv(1024).decode()
capitalized_sentence = sentence.upper()
print('Received from client ', addr, ": ", sentence)
connection_socket.send(capitalized_sentence.encode())
# 关闭该连接套接字,等待下一个连接
connection_socket.close()
实验结果:
客户端:
服务器端: