Python3 ConnectionResetError:[WinError 10054]远程主机强行关闭现有连接

时间:2016-11-21 09:04:21

标签: python-3.x sockets server connection client

我在python上创建了服务器+客户端代码。 目标如下:

  • 客户端向服务器发送命令。
  • 服务器接收命令,并运行一个函数来返回一些命令 信息取决于收到的命令。
  • 服务器还会添加一个包含ip-addresses的字符串 将客户连接到要返回的信息。
  • 服务器将其发送回客户端
  • 客户收到数据并使用它,但选择

服务器以python server.py启动。但对于客户端,您需要先导入它,导入客户端后,您可以这样调用它

nw = Client()
data = ''
try:
    nw.connect()
    nw.send_msg('Hello')
    data = nw.recv_msg()
    nw.close()
except:
    data = "An error Occurred"

上述客户端代码适用于服务器;但是,当我像这样运行代码时

item = "somethingthereandhere"
nw = Client()
data = "CMDGENERATE" + item
try:
    nw.connect()
    nw.send_msg(data)
    data = nw.recv_msg()
except:
    data = "An Error Occured"

我在服务器端出错了。回溯看起来像是

Accepted connection from ('127.0.0.1', 5381)
in recv_msg
in recvall
in recvall
Data received
in doing something
in lorem_gen
in send_msg
reply sent
in recv_msg
in recvall
Traceback (most recent call last):
  File "Slocket.py", line 92, in <module>
    new_client.connect()
  File "Slocket.py", line 25, in connect
    data = self.recv_msg(client)
  File "Slocket.py", line 43, in recv_msg
    raw_msglen = self.recvall(client, 4)
  File "Slocket.py", line 53, in recvall
    packet = client.recv(n - len(data))
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

服务器控制台上打印的所有信息都是跟踪器语句,以便知道解释器在任何位置的位置。 以下是服务器代码

#server.py
import socket
import struct
import time

class Server:

    def __init__(self, sock = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM)):
        self.clients = ''
        if sock is None:
            self.sock = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host="127.0.0.1", port=5007):
        self.sock.bind((host, port))
        self.sock.listen(20)
        print ("Listening on port: "+str(port))
        while True:
            client, sock_addr = self.sock.accept()
            print ("Accepted connection from", sock_addr)
            self.clients += "=========" + str(sock_addr)
            while True:
                    data = self.recv_msg(client)
                    if data is None: break
                    print("Data received")
                    reply = self.do_something(data)
                    self.send_msg(client, reply)
                    print('reply sent')
            client.close()
            print("Connection Closed")


    def send_msg(self, client, msg):
        print("in send_msg")
        msg = struct.pack('>I', len(msg)) + msg
        client.sendall(msg)


    def recv_msg(self,client):
        print("in recv_msg")
        raw_msglen = self.recvall(client, 4)
        if not raw_msglen:
            return None
        msglen = struct.unpack('>I', raw_msglen)[0]
        return self.recvall(client, msglen)

    def recvall(self, client, n):
        print("in recvall")
        data = ''
        while len(data) < n:
            packet = client.recv(n - len(data))
            if not packet:
                return None
            data += packet.decode()
        return data.encode()

    def do_something(self, data=""):
        print("in doing something")
        #change string to byte
        b = self.clients.encode()
        if 'CMDGENERATE'.encode() in data:
            data = lorem_gen(50)
        if 'CMDUPPERCASE'.encode() in data:
            data = data.upper()
        # add separator
        b += "====DD===".encode() + data
        if type(b) is str:
            b = b.encode()
        return b


def lorem_gen(n = 20):
    print("in lorem_gen")
    n = int(n)
    rd = "No file found or an error occured"
    a = " "
    try:
        srcfile =  open('data/lorem.txt', 'r')
        rd = srcfile.read()
        rd = rd.split(' ')
        rd = rd[0:n]
        a = ' '.join(rd)
        rd = a
    except:
        pass
    return rd.encode()



if __name__ == "__main__":
    new_client = Server()
    new_client.connect()

以下是客户端代码:

#client.py
import socket
import struct
import time

class Client:

    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host="127.0.0.1", port=5007):
        self.sock.connect((host, port))


    def send_msg(self, msg):
        msg = struct.pack('>I', len(msg)) + msg.encode()
        self.sock.sendall(msg)
        print("send_time", time.time())

    def recv_msg(self):
        raw_msglen = self.recvall(4)
        if not raw_msglen:
            return None
        print("raw_msglen is %s " % raw_msglen)
        msglen = struct.unpack('>I', raw_msglen)[0]
        print("msglen is %s " % msglen)
        return self.recvall(msglen)

    def recvall(self, n):
        data = ''
        while len(data) < n:
            packet = self.sock.recv(n - len(data))
            if not packet:
                return None
            data += packet.decode()
            print("receive_time", time.time())
        return data.encode()

    def close(self):
        print("close_time", time.time())
        return self.sock.close()

提前感谢您的帮助。

0 个答案:

没有答案