1. 客户端

# 1 创建套接字对象
import socket
# IPV4/TCP 协议
tcp_client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 2 和服务器端建立连接
tcp_client_socket.connect(('192.168.1.10',8080))
# 3 发送数据,必须是字节流
# encode(把字符串转为bytes) decode(把bytes转为字符串)
while True:
data = input('发送')
if data != '*':
data = data.encode('gbk')
tcp_client_socket.send(data)
# 4 接收服务器返回的数据  recv(字节大小)
recv_data = tcp_client_socket.recv(1024).decode('gbk')
print('服务器:', recv_data)
# 5 关闭套接字对象
else:
tcp_client_socket.close()
exit()


2. 服务器端

# 导入socket和threading
import socket
import threading
# 定义handle_client_request 循环以保持与客户端的连接,并能持续互相传递消息
def handle_client_request(service_client_socket,ip_port):
while True:
# 5 接收数据,最大接收为1024字符
recv_data = service_client_socket.recv(1024)
if recv_data:
print(recv_data.decode('gbk'),ip_port)  # 将二进制格式转换为'gbk'
# 6 服务器返回数据
back = f'自动回复:欢迎,您发送的数据为{recv_data.decode("gbk")}'
service_client_socket.send(back.encode('gbk'))  # 将'gbk'格式转换为二进制
else:
print('客户端下线',ip_port)
break
#  7 关闭套接字对象
service_client_socket.close()
if __name__ == '__main__':
# 1 创建套接字对象
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置端口号复用
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 2 绑定IP和端口,ip不写或写'127.0.0.1'都是主机本身
tcp_server_socket.bind(('',8080))
# 3 设置监听,一般为5,最大为128
tcp_server_socket.listen(5)
while True:
# 4 接收客户端套接字对象
service_client_socket, ip_port = tcp_server_socket.accept()
# 创建线程,传入套接字对象数据
sub_thread = threading.Thread(target=handle_client_request,args=(service_client_socket,ip_port))
# 守护主线程
sub_thread.setDaemon(True)
# 运行线程
sub_thread.start()