Reputation: 371
I want to connect via socket to my android app.but in server side(android app) I get java.net.SocketTimeoutException
error and in client side I get java.net.ConnectException: Connection refused: connect
error.
what is my mistake? thank you
server (android app)
public class ServerSocketTask extends AsyncTask<Void, Void, String> {
final StackTraceElement se = Thread.currentThread().getStackTrace()[2];
private String data = null;
@Override
protected String doInBackground(Void... params) {
Log.d(se.getClassName() + "." + se.getMethodName(), "start");
try {
ServerSocket serverSocket = new ServerSocket(8989);
serverSocket.setSoTimeout(50000);
Socket socket = serverSocket.accept();
socket.setKeepAlive(true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int readed = in.read();
Log.d("","readed bytes : "+readed);
String line;
while ((line = in.readLine()) != null){
Log.i("","line : "+ line);
}
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ServerSocketTask.this.data = result;
}
public String getData() {
return data;
}
}
client
public static void main(String[] args) {
int port;
try (Socket socket = new Socket("192.168.240.105", 8989)) {
String customerId = "123";
String requestId = Configuration.getProperty("requestId");
ClientService result = new ClientService();
String makeRequest = result.objectToJson(customerId, requestId);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.write(makeRequest);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
my client can't connect to server and my server wait for connection.
Upvotes: 2
Views: 2744
Reputation: 41678
When you construct ServerSocket(8989)
you're binding to wildcard address of network interfaces available on android emulator/device.
However both Android emulator and real device has it's own network interface(s) and thus it's it's own IP addresses. Your client program (development machine) IP address is not the same as IP address of android emulator/device. In other words you cannot connect to the socket created in Android app because you're using wrong address.
This answer should guide you on how to find out the address.
Upvotes: 2