TCP Client Socket. Connect and wait for input stream
android, java, sockets, tcp
Solution
try this may it works
Step 1
Remove these two lines:
serverAddr = InetAddress.getByName("192.168.11.254");
Socket clientSocket = new Socket(serverAddr, 5566);
Add this line:
Socket clientSocket = new Socket("192.168.11.254", 5566);
Step 2
Remove this code:
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (run) {
serverMessage = in.readLine();
mHandler.post(new DisplayToast(context, "TCP : " + serverMessage));
}
}
Add this code:
try {
char[] buffer = new char[2048];
int charsRead = 0;
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while ((charsRead = in.read(buffer)) != -1) {
String message = new String(buffer).substring(0, charsRead);
Log.e("In While", "msg :"+message);
}
}
Problem
I have a wifi sd card which sends me TCP packages with information about new images on the memory after I shoot a photo with the camera. On the terminal I can read the inputstream with this netcat command. netcat connects to ip 192.168.11.254 and listen on port 5566. the second line is the image path which I receive. ``` $ nc 192.168.11.254 5566 >/mnt/sd/DCIM/109_0302/IMGP0101.JPG ``` On my app I have a Java client socket which is connected to the same ip and port. But I don't receive the inputstream like in netcat, nothing happens. ``` void startListenForTCP (){ Thread TCPListenerThread = new Thread(new Runnable() { @Override public void run() { Boolean run = true; String serverMessage = null; InetAddress serverAddr = null; try { serverAddr = InetAddress.getByName("192.168.11.254"); Socket clientSocket = new Socket(serverAddr, 5566); try{ BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); while (run) { serverMessage = in.readLine(); mHandler.post(new DisplayToast(context, "TCP : " + serverMessage)); } } catch(UnknownHostException e) { mHandler.post(new DisplayToast(context, "UnknownHostException")); } catch(IOException e) { mHandler.post(new DisplayToast(context, "IOException")); } finally { clientSocket.close(); } } catch (IOException e) { e.printStackTrace(); } } }); TCPListenerThread.start(); } ```