0

hi I have an application that sends text to a device and the device shows it on a display. for transferring data I'm using socket in a AsyncTask class

            try {
                Socket socket = new Socket(DISPLAY_IP, DISPLAY_PORT);
                OutputStream out = socket.getOutputStream();
                PrintWriter output = new PrintWriter(out);
                output.println(params[0]);
                output.flush();
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

the problem is I can't read response from socket after sending data. when I'm getting input stream from socket and reading line I'm not getting anything and the device is not showing the sent data from me till I close the application so I think the socket is blocking when I'm doing that

           try {
                Socket socket = new Socket(DISPLAY_IP, DISPLAY_PORT);
                OutputStream out = socket.getOutputStream();
                PrintWriter output = new PrintWriter(out);
                output.println(params[0]);
                output.flush();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String response = bufferedReader.readLine();
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

how can I send data and read response from socket?

Amir_P
  • 8,322
  • 5
  • 43
  • 92
  • Not really sure what the problem is, but readLine() is *supposed* to hang - it will until a line is in fact sent by the other end (or until the connection times out or gets broken). I'd recommend trying to send the same message using netcat and seeing if you're getting a response - it might be a problem with the server, not the client. – SirGregg Jul 26 '17 at 16:44
  • the server is sending me `OK` after received data I just sent so what should I do? @SirGregg – Amir_P Jul 26 '17 at 16:57

2 Answers2

0

You are trying to communicate with two (client) Sockets. For communication you must implement on one side a (client) java.net.Socket and on the other a java.net.ServerSocket.

You may read further here.

PeterMmm
  • 24,152
  • 13
  • 73
  • 111
0

What are you trying to achieve? When using InputStream it will get data that came from other side, not the data that you just sent. And as SirGregg said readLine will hang until the whole line is received.

Serge-Zh
  • 26
  • 3
  • I need to know the server received my data so it sent me back a `OK` and I need to read it – Amir_P Jul 26 '17 at 16:58
  • @Amir_P Probably server does not sent \n, so line is not ended. readLine will wait end-of-line character – Serge-Zh Jul 26 '17 at 17:23