服务端代码
import socket
severname='127.0.0.1' #服务端的IP地址
severport=8888 #端口号
severSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #创建一个服务端
severSocket.bind((severname,severport)) #将服务端与刚刚的IP地址和端口号绑定在一起
severSocket.listen(1) #开始监听消息
print("The sever is ready to receive")
conn,client_addr=severSocket.accept() #获得连接的客户端的相关信息
while True:
# 接收消息
data = b''
while True:
data_s=conn.recv(1024)
data=data+data_s
if len(data_s) <= 1024:
break
if data==None:
continue
else:
print('客户端发来的数据:',data.decode('utf-8'))
if data.decode('utf-8')=='有内鬼,终止交易':
conn.send('有内鬼,终止交易'.encode('utf-8'))
break
# 发送消息
message=input()
if message == None:
continue
conn.send(message.encode('utf-8'))
print('消息已发送')
conn.close()
print('结束通信')
severSocket.close()
print('关机')
客户端代码
import socket
delientSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #创建一个客户端
delientSocket.connect(('127.0.0.1',8888)) #客户端发出连接IP地址为127.0.0.1的主机中端口号为8888的服务端进程
while True:
#发送消息
message=input()
if message == None:
continue
delientSocket.send(message.encode('utf-8'))
print('消息已发送')
#接收消息
data=b''
while True:
data_s=delientSocket.recv(1024)
data=data+data_s
if len(data_s) <= 1024:
break
if data == None:
continue
else:
print('服务端发来的数据:', data.decode('utf-8'))
if data.decode('utf-8')=='有内鬼,终止交易':
delientSocket.send('有内鬼,终止交易'.encode('utf-8'))
break
delientSocket.close()
print('通信结束')
运行结果