Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用套接字从Python向Java发送字节?_Java_Python_Image_Sockets_Networking - Fatal编程技术网

如何使用套接字从Python向Java发送字节?

如何使用套接字从Python向Java发送字节?,java,python,image,sockets,networking,Java,Python,Image,Sockets,Networking,我读过一些关于如何在Python中使用套接字发送图片以及如何在Java中使用套接字发送图片的帖子,我想将两者结合起来,并使用两端的套接字将图片从Python发送到Java。我的大部分代码取自我读过的文章,但这里是python客户端: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("192.168.0.12",4141)) try: file = open("subbed

我读过一些关于如何在Python中使用套接字发送图片以及如何在Java中使用套接字发送图片的帖子,我想将两者结合起来,并使用两端的套接字将图片从Python发送到Java。我的大部分代码取自我读过的文章,但这里是python客户端:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect(("192.168.0.12",4141))

try:

    file = open("subbed.jpg", 'rb')
    bytes = file.read()
    print "{0:b}".format(len(bytes))
    size = len(bytes)
    s.sendall(size)

    answer = s.recv(4096)
    print "Answer = %s" %answer 

    if answer == 'GOT SIZE':
        s.sendall(bytes)

        answer = s.recv(4096)

        if answer == 'GOT IMAGE' :
            s.sendall("byte")
    file.close()
finally:
    s.close()
Java服务器的代码是:

public static void main(String[] args) {
    while(true) {
        try (
                ServerSocket server = new ServerSocket(PORT_NUMBER);
                Socket client = server.accept();
                PrintWriter out = new PrintWriter(client.getOutputStream(), true);
                InputStream in = client.getInputStream()) {
            System.out.println("GOT CONNECTION FROM: " + client.getInetAddress().toString());
            byte[] sizeAr = new byte[4];

            in.read(sizeAr);
            int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();
            System.out.println(Integer.toBinaryString(size));
            out.println("GOT SIZE");

            byte[] imageAr = new byte[size];
            in.read(imageAr);

            BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));
            ImageIO.write(image, "jpg", new File("C:\\myprivatelocation\\test.jpg"));

        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
    }
}

最初的问题来自发送我认为的大小。我不是python专家,也不是Java专家,但我认为现在的情况是python将大小作为字符串发送,Java将其作为字节数组接收并将其转换为整数,这两种语言的存储方式存在一些差异。有人能在这个问题上提供帮助吗

某些内容已关闭-尝试在套接字中发送某个整数时,您应该会遇到某种错误:

>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('localhost', 7777))
>>> s.sendall(len(b'some bytes'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'int'

同样,您应该使用
struct.unpack
将字节转换回整数对象。有关更多详细信息和可能的转换表,请参见。

尽管我会以稍微不同的方式处理您的问题,但以下代码仍然有效:

Python发送方

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect(("127.0.0.1", 8888))

    with open("C:\\temp\\test-input.jpg", 'rb') as f:
        content = f.read()

    size = len(content)
    print("File bytes:", size)
    s.sendall(size.to_bytes(4, byteorder='big'))

    buff = s.recv(4)
    resp = int.from_bytes(buff, byteorder='big')
    print("Response:", resp)

    if size == resp:
        s.sendall(content)

    buff = s.recv(2)
    print(buff)

print("Complete.")
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;


import javax.imageio.ImageIO;

class Server{
    public static void main(String[] args) {
        int PORT_NUMBER = 8888;

        try (
            ServerSocket server = new ServerSocket(PORT_NUMBER);
            Socket client = server.accept();
            OutputStream sout = client.getOutputStream();
            InputStream sin = client.getInputStream();
        ){
            System.out.println("GOT CONNECTION FROM: " + client.getInetAddress().toString());

            // Get length
            byte[] size_buff = new byte[4];
            sin.read(size_buff);
            int size = ByteBuffer.wrap(size_buff).asIntBuffer().get();
            System.out.format("Expecting %d bytes\n", size);

            // Send it back (?)
            sout.write(size_buff);

            // Create Buffers
            byte[] msg_buff = new byte[1024];
            byte[] img_buff = new byte[size];
            int img_offset = 0;
            while(true) {
                int bytes_read = sin.read(msg_buff, 0, msg_buff.length);
                if(bytes_read == -1) { break; }

                // Copy bytes into img_buff
                System.arraycopy(msg_buff, 0, img_buff, img_offset, bytes_read);
                img_offset += bytes_read;
                System.out.format("Read %d / %d bytes...\n", img_offset, size);

                if(img_offset >= size) { break; }
            }
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(img_buff));
            ImageIO.write(image, "jpg", new File("C:\\temp\\test-output.jpg"));

            // Send "OK"
            byte[] OK = new byte[] {0x4F, 0x4B};
            sout.write(OK);
        }
        catch (IOException ioe) { ioe.printStackTrace(); }
    }
}
Java接收器

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect(("127.0.0.1", 8888))

    with open("C:\\temp\\test-input.jpg", 'rb') as f:
        content = f.read()

    size = len(content)
    print("File bytes:", size)
    s.sendall(size.to_bytes(4, byteorder='big'))

    buff = s.recv(4)
    resp = int.from_bytes(buff, byteorder='big')
    print("Response:", resp)

    if size == resp:
        s.sendall(content)

    buff = s.recv(2)
    print(buff)

print("Complete.")
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;


import javax.imageio.ImageIO;

class Server{
    public static void main(String[] args) {
        int PORT_NUMBER = 8888;

        try (
            ServerSocket server = new ServerSocket(PORT_NUMBER);
            Socket client = server.accept();
            OutputStream sout = client.getOutputStream();
            InputStream sin = client.getInputStream();
        ){
            System.out.println("GOT CONNECTION FROM: " + client.getInetAddress().toString());

            // Get length
            byte[] size_buff = new byte[4];
            sin.read(size_buff);
            int size = ByteBuffer.wrap(size_buff).asIntBuffer().get();
            System.out.format("Expecting %d bytes\n", size);

            // Send it back (?)
            sout.write(size_buff);

            // Create Buffers
            byte[] msg_buff = new byte[1024];
            byte[] img_buff = new byte[size];
            int img_offset = 0;
            while(true) {
                int bytes_read = sin.read(msg_buff, 0, msg_buff.length);
                if(bytes_read == -1) { break; }

                // Copy bytes into img_buff
                System.arraycopy(msg_buff, 0, img_buff, img_offset, bytes_read);
                img_offset += bytes_read;
                System.out.format("Read %d / %d bytes...\n", img_offset, size);

                if(img_offset >= size) { break; }
            }
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(img_buff));
            ImageIO.write(image, "jpg", new File("C:\\temp\\test-output.jpg"));

            // Send "OK"
            byte[] OK = new byte[] {0x4F, 0x4B};
            sout.write(OK);
        }
        catch (IOException ioe) { ioe.printStackTrace(); }
    }
}
发送方打开一个套接字,读取文件,然后将长度发送给接收方。接收器获取长度,解析字节并将其发回。收到“确认”后,发送方将发送文件内容。然后,接收器将从套接字输入流中重复读取1024字节块,并将字节插入
img_数据
。当不再需要字节(或套接字关闭)时,接收方将向发送方发送“OK”(无条件)并退出。发送方只需打印“OK”(以字节为单位),然后退出


其中一些问题可以用
ByteArrayOutputStream来解决,但我希望尽可能接近代码的功能。

谢谢,您的解决方案对我来说效果很好。现在你能告诉我为什么我的解决方案不起作用吗?