0

我正在编写一个 Java 客户端,它将图像作为字节数组发送,而 Python 服务器则用于接收图像。接收到的图像高度、宽度、通道是否正确,

sock = socket.socket()
sock.bind(('localhost', 8080))
sock.listen(1)
print ("Listen")
conn, addr = sock.accept()

print('Start server')
while True:
    data = conn.recv(1024)
    if not data:
        break
    img = cv2.imdecode(np.fromstring(io.BytesIO(data).getvalue(), dtype=np.uint8), 1)
    np.save('snapshot.npy',img)
    exit()

使用显示图像cv2.imshow('img', img)会产生不正确的结果:示例输出

Java端:

public class Client implements Runnable {

private Socket socket;
private DataOutputStream out;
private String server;
private int port;

private ArrayList<ResponseListener> listeners = new ArrayList<>();

public void addListener(ResponseListener responseListener){
    listeners.add(responseListener);
}

public void removeListeners(ResponseListener responseListener){
    listeners.remove(responseListener);
}

Client(String server, int port) {
    this.server = server;
    this.port = port;
}

public void start(){
    while(socket==null){
        try {
            socket = new Socket(server, port);
            socket.setTcpNoDelay(true);
            System.out.println("Ready");
            listeners.forEach((listener)->listener.serverIsReady());
        } catch (Exception ex) {
            System.out.println("In thread " + ex.toString());
        }
    }
}

public void send(byte[] img) throws IOException {
    out.write(img);
}

@Override
public void run() {

    InputStreamReader in = null;
    try {
        in = new InputStreamReader(socket.getInputStream());
        System.out.println(in);
        out = new DataOutputStream(socket.getOutputStream());
    } catch (IOException e) {
        System.out.println("in or out failed");
        System.exit(-1);
    }
    int count = 0;
    while (true) {
        try {
            int line = in.read();
            count++;
            if(count==4) {
                listeners.forEach((listener)->listener.onSignDefined(String.valueOf(line)));
                count=0;
            }
        } catch (Exception e) {
            System.out.println("In loop " + e.toString());
            System.exit(-1);
        }
    }
}

}

4

1 回答 1

0

我解决了问题。解决方案非常简单:data = conn.recv(640*480*3)

640*480*3 - 图片尺寸

于 2017-06-10T20:22:28.870 回答