简体   繁体   English

TCP套接字上的多个图像文件

[英]Multiple image files on a TCP socket

I am trying to send multiple images on a TCP socket. 我正在尝试在TCP套接字上发送多个图像。

The following code is running fine without a problem: the client and server exchange a greeting. 以下代码运行正常,没有问题:客户端和服务器交换问候。 Then the client is sending a single image file which the server receives. 然后,客户端将发送服务器接收的单个图像文件。

Client side: 客户端:

...        
try      {
    Socket clientSocket = new Socket(serverName, port);
    DataInputStream in=new DataInputStream(clientSocket.getInputStream());
    System.out.println("Heard from server: "+in.readUTF());

    DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
    out.writeUTF("Hello from " + clientSocket.getLocalSocketAddress());

    BufferedImage bimg;

//    for (int i=0; i<3; i++)  {
    bimg = ImageIO.read(new File("flowers.jpg"));  
    ImageIO.write(bimg,"jpg",clientSocket.getOutputStream());   
    out.flush(); 
    System.out.println("Image sent");
//    }
    clientSocket.close();
  } catch(Exception e) { ... }

Server side: 服务器端:

...
Socket socket=null;
DataInputStream din=null;
DataOutputStream dout=null;
...
socket = serverSocket.accept();  
din=new DataInputStream(socket.getInputStream());
dout=new DataOutputStream(socket.getOutputStream());

for (;;)  {  
    try  {

        dout.writeUTF("ImageReceiver here at your service: ");

        System.out.println("from the client: "+din.readUTF());
        BufferedImage img;

//for (int i=0; i<3; i++) {
        img=ImageIO.read(socket.getInputStream());   
        ImageIO.write(img, "png", new File(timeStamp+"img.png"));
        System.out.println("Image received...");
//} 
        socket.close();
        break;
   }
  catch(Exception e) {  .... }
 }

When I uncomment the 2*2 lines in the above and thus send&receive images in a loop, I am getting an exception that the image is null: 当我取消注释上面的2 * 2行并因此在循环中发送和接收图像时,出现了图像为空的异常:

the server is receiving the 1st image fine without errors. 服务器正在正确接收第一张图像,没有错误。 However, after that, it is not seeing the input stream as an image. 但是,此后,它不会将输入流视为图像。 The call to ImageIO.read() at 在以下位置调用ImageIO.read()

img=ImageIO.read(socket.getInputStream());    

is returning null and 返回null和

        ImageIO.write(img, "png", new File(timeStamp+"img.png"));

is throwing the exception. 引发异常。

The client process is running fine without any errors. 客户端进程运行正常,没有任何错误。

Is this a matter of managing the I/O buffers? 这是管理I / O缓冲区的问题吗?

Where to look to fix it? 在哪里寻找解决方案?

TIA. TIA。

//======================================= // ======================================

I'm getting the same error when I'm sending 2 images: the first image is transmitted&received fine. 发送2张图像时出现相同的错误:第一张图像发送和接收正常。

The client is sending the second image as the last thing before it closes. 客户端在关闭之前将第二张图像作为最后的内容发送。 However, the server isn't seeing the second one as an image. 但是,服务器看不到第二个作为图像。 After the first image is transmitted, there's nothing in the server-socket's input buffer but the second image. 传输第一个图像后,服务器套接字的输入缓冲区中只有第二个图像。

ImageIO closes the input stream after reading the image.It needs to be created again and again for reading multiple images using ImageIO.createImageInputStream(). ImageIO在读取图像后关闭输入流,需要使用ImageIO.createImageInputStream()一次又一次创建它以读取多个图像。 You can see it here- https://docs.oracle.com/javase/8/docs/api/javax/imageio/ImageIO.html#read-javax.imageio.stream.ImageInputStream- 您可以在这里看到它-https : //docs.oracle.com/javase/8/docs/api/javax/imageio/ImageIO.html#read-javax.imageio.stream.ImageInputStream-

You can try this code. 您可以尝试此代码。 This code sends data in bytes. 此代码以字节为单位发送数据。

client (Sender): 客户(发件人):

try {
        int port = 8989; // Your Server port number
        Socket sender = new Socket("Server IP", port);
        int count,i=0;

        byte[] data = new byte[1024]; // Here provide size of your file
        FileInputStream fileStream = null;
        BufferedInputStream fileBuffer = null;
        OutputStream out = sender.getOutputStream();
        InputStream in = sender.getInputStream();

        while (i < 10) {

            fileStream = new FileInputStream("fileURL");
            fileBuffer = new BufferedInputStream(fileStream);

            // Sending file data in bytes
            while ((count = fileBuffer.read(data)) > 0) {
                System.out.println("Data Sent : " + count);
                out.write(data, 0, count);
                out.flush();
            }

            // Waiting for response
            while (in.available() <= 0) {
            }
            if (in.read() == 0) {
                System.out.println("File Sent Successfully");
                i++;
            } else {
                System.out.println("File Not Sent Successfully");
            }
        }
    } catch (Exception e) {
    }

Server (Receiver): 服务器(接收方):

try {
        ServerSocket server = new ServerSocket(port);

        // Waiting for client
        Socket receiveSocket = server.accept();
        InputStream in = receiveSocket.getInputStream();
        OutputStream out = receiveSocket.getOutputStream();
        int count, cnt = 10, i = 0;

        // cnt will be total number of files
        while (i < cnt) {
            byte data[] = new byte[1024]; // Provide file size here
            FileOutputStream fileOut = new FileOutputStream("fileURL");
            BufferedOutputStream fileBuffer = new BufferedOutputStream(fileOut);

            // Waiting till client is sending the file
            while (in.available() <= 0) {
            }
            // Receiving byte data and storing it in the file
            while ((count = in.read(data)) > 0) {
                fileBuffer.write(data, 0, count);
                System.out.println("Data Received : " + count);
                fileBuffer.flush();
            }
            // Notify client that you received that file successfully
            out.write(0);

            // Close all streams
            in.close();
            out.close();
            fileBuffer.close();
            fileOut.close();
            i++;
        }
    } catch (Exception e) {
    }

Hope this helps you. 希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM