套接字不是recv numpy数组

时间:2017-06-21 13:34:49

标签: python arrays sockets numpy

我有一个问题,我创建了多处理服务器,但是当我发送numpy数组时,我的客户端在无限循环中运行,这是我的代码:

服务器: 我认为我的服务器代码很好。

import socket, pickle
import numpy as np
from PIL import ImageGrab
import cv2
import logging
import multiprocessing

def handle(connection, address):
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger("process-%r" % (address,))
    try:
        logger.debug("Connected %r at %r", connection, address)
        while True:
            data = connection.recv(1024)
            printscreen_pil=ImageGrab.grab(bbox=(10,10,500,500))
            img = np.array(printscreen_pil) ## Transform to Array
            data_string = pickle.dumps(img)
            if data == "":
                logger.debug("Socket closed remotely")
                break
            logger.debug("Received data %r", data)
            connection.sendall(data_string)
            logger.debug("Sent data")
    except:
        logger.exception("Problem handling request")
    finally:
        logger.debug("Closing socket")
        connection.close()

class Server(object):
    def __init__(self, hostname, port):
        self.logger = logging.getLogger("server")
        self.hostname = hostname
        self.port = port

    def start(self):
        self.logger.debug("listening")
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind((self.hostname, self.port))
        self.socket.listen(1)

        while True:
            conn, address = self.socket.accept()
            self.logger.debug("Got connection")
            process = multiprocessing.Process(target=handle, args=(conn, address))
            process.daemon = True
            process.start()
            self.logger.debug("Started process %r", process)


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    server = Server("0.0.0.0", 9000)
    try:
        logging.info("Listening")
        server.start()
    except:
        logging.exception("Unexpected exception")
    finally:
        logging.info("Shutting down")
        for process in multiprocessing.active_children():
            logging.info("Shutting down process %r", process)
            process.terminate()
            process.join()
    logging.info("All done")

但客户端,我认为错误是在我的循环中而真实

import socket, pickle
import numpy as np
import cv2

if __name__ == "__main__":
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("localhost", 9000))
    data = "some data"
    sock.sendall(data.encode())

    data = []
    while True:
        packet = sock.recv(1024)
        if not packet: break
        data.append(packet)
        print("toto")
    data_arr = pickle.loads(b"".join(data))
    print(data_arr)
    sock.close()

0 个答案:

没有答案