服务端:
from socket import *
server_socket = socket(AF_INET, SOCK_STREAM)
bind_addr = ('', 7788)
server_socket.bind(bind_addr)
server_socket.listen(5)
while True:
client_socket, client_addr = server_socket.accept()
# 当有新的客户端连接进来,就会产生一个新的套接字,client_socket将为这个新的客户端服务
# server_socket只被用来等待其他客户端连接
while True:
revc_data = client_socket.recv(1024)
if len(revc_data) > 0:
print('recv:%s' % revc_data.decode('gbk'))
else:
break # 当接收到的数据长度小于等于0时则意味着客户端已被关闭
# 客户端退出后发送一句话给它
send_data = input('send:')
client_socket.send(send_data.encode('gbk'))
# 当客户关闭客户端,则断掉连接
client_socket.close() # 当while 退出后关闭
server_socket.close()
客户端:
from socket import *
client_socket = socket(AF_INET, SOCK_STREAM)
conn_addr = ('127.0.0.1', 7788)
client_socket.connect(conn_addr)
while True:
send_data = input('send:')
if len(send_data) > 0:
client_socket.send(send_data.encode('gbk'))
else:
break
# 接收服务端发送来的数据
recv_data = client_socket.recv(1024)
print('收到的数据为%s' % recv_data.decode('gbk'))
client_socket.close() # 当while退出后关闭