Python socket.error: [Errno 104] 对等方重置连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33981141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python socket.error: [Errno 104] Connection reset by peer
提问by potockan
I have a code where there are 13 clients that have to connect to the server. Then the server does some counting on the data given by the client. After that the roles turns around - the server becomes a client and clients become servers to receive the data.
The thing is that when trying to do the first connection, that is when the 13 clients try to connect to the server I keep getting this error: [Errno 104] Connection reset by peer
. I tried some workarounds for example trying to connect 5 times in a second interval but nothing works.
我有一个代码,其中有 13 个客户端必须连接到服务器。然后服务器对客户端提供的数据进行一些计数。之后角色转换 - 服务器成为客户端,客户端成为接收数据的服务器。问题是,当尝试进行第一次连接时,即当 13 个客户端尝试连接到服务器时,我不断收到此错误: [Errno 104] Connection reset by peer
。我尝试了一些解决方法,例如尝试在第二个时间间隔内连接 5 次,但没有任何效果。
Here my code:
这是我的代码:
server.py
服务器.py
import socket, pickle, numpy as np
import struct
import math
while 1:
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(13)
adresses = []
ports = []
i = 0
print("receiving...")
while i < 13:
i += 1
#wait to accept a connection - blocking call
conn, addr = s.accept()
print ('Connected with ', addr)
adresses.append(addr[0])
buf = b''
while len(buf) < 4:
buf += conn.recv(4 - len(buf))
length = struct.unpack('>I', buf)[0]
data = b''
l = length
while l > 0:
d = conn.recv(l)
l -= len(d)
data += d
if not data: break
M = np.loads(data)
if i == 1:
L = M[0]
else:
L += M[0]
ports.append(M[1])
conn.close()
s.close()
L /= 993040
packet = pickle.dumps(L)
length = struct.pack('>I', len(packet))
packet = length + packet
print("sending...")
for kl, addr in enumerate(adresses):
HOST = addr
PORT = 50007 + ports[kl]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(packet)
s.close()
client.py
客户端.py
def connection(centers, kl):
HOST = "192.168.143.XX"
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3600)
try:
s.connect((HOST, PORT)) # HERE IS AN ERROR
s.settimeout(None)
packet = pickle.dumps([centers, kl]) ## ???
length = struct.pack('>I', len(packet))
packet = length + packet
s.sendall(packet) # OR HERE IS AN ERROR
s.close()
except Exception as e:
print(e)
print('error ', kl)
s.close()
return np.zeros(centers.shape)
HOST = ''
PORT = 50007 + kl
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2)
i = 0
while i < 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
i += 1
print ('Connected with ', addr)
buf = b''
while len(buf) < 4:
buf += conn.recv(4 - len(buf))
length = struct.unpack('>I', buf)[0]
data = b''
l = length
while l > 0:
d = conn.recv(l)
l -= len(d)
data += d
if not data: break
new_centers = np.loads(data)
conn.close()
s.close()
return new_centers
aa = 0
for k in range(99):
print(k)
centers = some_function(centers)
time.sleep(60)
centers1 = connection(centers, i)
aa = 0
while not (centers1.any()) and aa < 5:
time.sleep(1)
centers1 = connection(centers, i)
aa += 1
centers = centers1
The thing is all of the 13 clients HAVE TO connect to the server or it won't proceed to the next iteration. I'm using Python 3.4. Please help.
问题是所有 13 个客户端都必须连接到服务器,否则将无法进行下一次迭代。我正在使用 Python 3.4。请帮忙。
Update:
更新:
I have added threads but the error remains:
我添加了线程,但错误仍然存在:
[Errno 104] Connection reset by peer
[Errno 104] 对等方重置连接
server.py
服务器.py
import socket, pickle, numpy as np
import struct
import math
from multiprocessing.pool import ThreadPool
def clientthread(conn, L):
buf = b''
while len(buf) < 4:
buf += conn.recv(4 - len(buf))
length = struct.unpack('>I', buf)[0]
data = b''
l = length
while l > 0:
d = conn.recv(l)
l -= len(d)
data += d
M = np.loads(data)
return(M)
j = 0
while 1:
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2)
#print('0')
adresses = []
ports = []
i = 0
print("receiving...")
while i < 13:
i += 1
#wait to accept a connection - blocking call
conn, addr = s.accept()
print ('Connected with ', addr)
adresses.append(addr[0])
pool = ThreadPool(processes=13)
async_result = pool.apply_async(clientthread, (conn, i,))
M = async_result.get()
conn.close()
if i == 1:
L = M[0]
else:
L += M[0]
ports.append(M[1])
s.close()
L /= 993040
packet = pickle.dumps(L)
length = struct.pack('>I', len(packet))
packet = length + packet
for kl, addr in enumerate(adresses):
HOST = addr
PORT = 50007 + ports[kl]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(packet)
s.close()
回答by Rolf of Saxony
You are going to have to use threading on the server.
For a simple explanation see: http://www.binarytides.com/python-socket-server-code-example/
The guts of the simple example given there is:
您将不得不在服务器上使用线程。
有关简单说明,请参阅:http: //www.binarytides.com/python-socket-server-code-example/
给出的简单示例的内容是:
import socket
import sys
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
回答by Mahyar Hosseini
It seems that the clients were connected to the server but they encountered with " [Errno 104] Connection reset by peer
" exception when they tried to send data. For the first time, Python raises "[Errno 104] Connection reset by peer" exception, then for the second time and more you would get "[Errno 32] Broken pipe" exception on the client side.
客户端似乎已连接到服务器,但[Errno 104] Connection reset by peer
在尝试发送数据时遇到了“ ”异常。Python第一次引发“[Errno 104] Connection reset by peer”异常,然后第二次和更多你会在客户端得到“[Errno 32] Broken pipe”异常。
This can mean that the server is up and listening on the port (otherwise, you would get "[Errno 111] Connection refused" exception on the client side
". This also means that the server is crashed before closing the connection since if the connection was closed on the server side before sending data on the client side, the client would encounter with "[Errno 32] Broken pipe
" exception.
这可能意味着服务器已启动并正在侦听端口(否则,您会得到“ [Errno 111] Connection refused" exception on the client side
”。这也意味着服务器在关闭连接之前崩溃了,因为如果在客户端发送数据之前在服务器端关闭了连接一边,客户端会遇到“ [Errno 32] Broken pipe
”异常。
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From another stackoverflow answer)
“由对等方重置连接”是 TCP/IP 等价物,相当于将电话重新挂断。这比仅仅不回复而留下一个悬而未决更有礼貌。但这不是真正礼貌的 TCP/IP 对话者所期望的 FIN-ACK。(来自另一个stackoverflow答案)
回答by StingyHyman
I had this exact error when trying to connect to a remote redis instance from python, because I had mistakenly left Fiddler running and it was interfering with the requests.
尝试从 python 连接到远程 redis 实例时,我遇到了这个确切的错误,因为我错误地让 Fiddler 运行并且它干扰了请求。