嗨,我为服务器和客户端之间的点对点聊天编写了简单的聊天程序。此代码适用于客户端,客户端可以发送消息,服务器接收该消息。但是对于服务器端,当我想发送消息时,我在第 40 行有错误
File "server.py", line 40, in <module>
newSocket.send('\r<Server>: ' + msg)
socket.error: [Errno 32] Broken pipe
和服务器崩溃。
服务器 :
import socket
import os
import select
import sys
def prompt():
sys.stdout.write('Server : ')
sys.stdout.flush()
try:
newSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
newSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except:
print 'socket Error'
sys.exit(1)
newSocket.bind(('127.0.0.1', 8000))
newSocket.listen(5)
input_list = [newSocket, sys.stdin]
print 'Chat Program'
prompt()
while True:
inputready, outputready, exceptready = select.select(input_list,[],[])
for sock in inputready:
if sock == newSocket:
(client, (ip, port)) = newSocket.accept()
input_list.append(client)
data = client.recv(2048)
if data:
sys.stdout.write(data)
elif sock == sys.stdin:
msg = sys.stdin.readline()
newSocket.send('\r<Server>: ' + msg)
prompt()
else:
data = sock.recv(2048)
if data:
sys.stdout.write(data)
newSocket.close()
客户 :
import socket
import os
import select
import sys
def prompt():
sys.stdout.write('Client ')
sys.stdout.flush()
try:
newSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
newSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except:
print 'socket Error'
sys.exit(1)
newSocket.connect(('127.0.0.1', 8000))
print 'Connected to remote host. Start sending messages'
prompt()
while 1:
socket_list = [sys.stdin, newSocket]
read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])
for sock in read_sockets:
if sock == newSocket:
data = sock.recv(4096)
if not data:
print '\nDisconnected from chat server'
sys.exit()
else:
sys.stdout.write(data)
prompt()
else:
msg = sys.stdin.readline()
newSocket.send('\r<Client>: ' + msg)
prompt()