import socket
# 创建一个TCP Socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 将Socket对象绑定到本地主机的8080端口
sock.bind(('localhost', 8080))
# 开始监听连接请求
sock.listen(5)
while True:
# 接受连接请求
client_sock, client_addr = sock.accept()
# 接收客户端发送的数据
data = client_sock.recv(1024)
# 打印接收到的数据
print('Received:', data)
# 发送数据给客户端
client_sock.send(b'Hello Client')
# 关闭客户端Socket连接
client_sock.close()
客户端代码
import socket
# 创建一个TCP Socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 发起连接请求
sock.connect(('localhost', 8080))
# 发送数据给服务器
sock.send(b'Hello Server')
# 接收服务器发送的数据
data = sock.recv(1024)
# 打印接收到的数据
print('Received:', data)
# 关闭Socket连接
sock.close()