简体   繁体   中英

Receiving byte array over a socket

i have a program which accepts connection from a phone that sends a byte array, i am able to test the connection when it is made, however how do i know that i am actually receiving something? how can i "see" if any thing is being sent over the socket. Because from my code below i am not able to have the resulting file "saved.jpg" created. Does this mean that it did not receive anything?

public class wpsServer {

    //vars
    private int svrPort = 3334;
    private ServerSocket serverSocket;
    private Image image = null;

    public wpsServer()
    {
        try {
             serverSocket = new ServerSocket(svrPort);
             System.out.println("Server started on "+svrPort);
        } 
        catch (IOException e) {
            System.out.println("Could not listen on port: "+svrPort);
            System.exit(-1);
        }
    }

    public void listenForClient()
    {
        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
            if(clientSocket.isConnected())
                System.out.println("Connected");

          byte[] pic = getPicture(clientSocket.getInputStream());
          InputStream in = new ByteArrayInputStream(pic);
          BufferedImage image = ImageIO.read(in);
          File outputfile = new File("saved.jpg");
          ImageIO.write(image, "jpg", outputfile);

        } 
        catch (IOException e) {

            System.out.println("Accept failed: "+svrPort);
            System.exit(-1);
        }

    }

    public byte[] getPicture(InputStream in) {
          try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] data = new byte[1024];
            int length = 0;
            while ((length = in.read(data))!=-1) {
                out.write(data,0,length);
            }
               return out.toByteArray();
            } catch(IOException ioe) {
            //handle it
           }
           return null;
         }

}

The in.read call will only return -1 if the other end closes the socket. While the socket is alive, that call will block until more data is available.

What you need to do is change your "protocol": the client should send the array size first, then the data. The server should read that length, and stop reading the file when that's done (go back to waiting for the next file for instance).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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