在实际的开发过程中经常会开发服务端、客户端的方式进行数据的收、发,这样便于进行管理
服务端
from socket import socket, AF_INET, SOCK_STREAM
server = socket(AF_INET, SOCK_STREAM)
# 不添加IP地址,默认表示本机
server.bind(('', 9090))
server.listen(5)
while True:
sock, addr_info = server.accept()
while True:
data = sock.recv(1024).decode('utf-8')
print(f'客户端推送:{data}')
if data == 'bye':
break
msg = input('服务器输入:')
sock.send(msg.encode('utf-8'))
if msg == 'bye':
break
sock.close()
客户端
from socket import socket, AF_INET, SOCK_STREAM
client = socket(AF_INET, SOCK_STREAM)
con_address = ('IP地址这里不展示', 9090)
client.connect(con_address)
while True:
msg = input('客户端输入:')
client.send(msg.encode('utf-8'))
if msg == 'bye':
break
recv_msg = client.recv(1024).decode('utf-8')
print(f'服务器返回:{recv_msg}')
if recv_msg == 'bye':
break
client.close()
运行结果: