0

Java sending and receiving file (byte[]) over sockets

referring to the above question i just wanted to ask how can i put this code in loop for recieving multiple images from client side ???? I have tried but it doesnot stop at (count = is.read(bytes)) > 0 once it has read first time. Pleas help

Community
  • 1
  • 1
Wajih Ahmed
  • 99
  • 1
  • 2
  • 7

1 Answers1

0

I am not actually sure that I understand your question exactly, but I will try to help. So you want to have connection client/server for infinite amount of time? So try making both the server client and the client itself as threads and then put the tread in a loop. Try this sample.

connection = new Socket("IP",PORT);
        input = new DataInputStream(connection.getInputStream());
        output = new DataOutputStream(connection.getOutputStream());
        new Thread(new Runnable() {

        public void run(){
            while(true){
            try
            {
                System.out.println(">>" + input.readUTF());
            }
            catch(Exception e){
                try
                {
                    input.close();
                    output.close();
                    connection.close();
                }
                catch(Exception e2)
                {}
             }
            }
        }
        }).start(); 

        Scanner scan = new Scanner(System.in);

        while(true)
        {
            String data = scan.nextLine();
            output.writeUTF(data);
        }

This is the code for the client. You must also have ClienT Service thread that accepts all the data and sends back info! Hope I was helpful, because I am not really sure I understood the question correctly. Good Luck!

  • yes i want to have connection between client and server for infinite time i.e in a while loop – Wajih Ahmed Apr 06 '13 at 10:05
  • `readUTF()` only works if the peer is using `writeUTF()`, and they both only work if the data is text. None of these things is stated inthe answer or even the question. Exceptions should not be merely ignored, and in this case `EOFException` must be caught separately. Answer is completely incorrect. – user207421 Sep 09 '19 at 04:18