The mentioned discussion in StackOverflow - wasn't helpful for me
I'm trying to make a client running on Android emulator, connect to my server running on eclipse in the same machine. The server is configured to listen on port 5000. The server doesn't appear to be the problem. When I run a Client on eclipse they can open a socket and communicate. When I try to run the Client class on Android emulator, the mainActivity tells the client to connect when it is created. but from some reason the dbugging flow reach the catch block, instead of creating the socket.
I tried using also client.connect("10.0.2.2",5000);
but it didn't help.
MainActivity.java
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Client client = new Client(this);
try {
client.connect("192.168.1.10",5000);
} catch (IOException e) {
e.printStackTrace();
}
}
Client.java
package com.example.oshri.p;
import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;
public class Client extends Observable implements Runnable {
MainActivity creatingActivity; // the activity that creates Client
private Socket socket;
private BufferedReader br;
private PrintWriter pw;
private boolean connected;
private int port=5555; //default port
private String hostName="localhost";//default host name
public Client(MainActivity activity) {
connected = false;
this.creatingActivity = activity;
}
public void connect(String hostName, int port) throws IOException {
if(!connected)
{
this.hostName = hostName;
this.port = port;
socket = new Socket(hostName,port);
//get I/O from socket
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
connected = true;
//initiate reading from server...
Thread t = new Thread(this);
t.start(); //will call run method of this class
}
}
public void sendMessage(String msg) throws IOException
{
if(connected) {
pw.println(msg);
} else throw new IOException("Not connected to server");
}
public void disconnect() {
if(socket != null && connected)
{
try {
socket.close();
}catch(IOException ioe) {
//unable to close, nothing to do...
}
finally {
this.connected = false;
}
}
}
public void run() {
String msg = ""; //holds the msg recieved from server
try {
while(connected && (msg = br.readLine())!= null)
{
creatingActivity.displayServerAnswer("Server:"+msg);
this.setChanged();
this.notifyObservers(msg);
}
}
catch(IOException ioe) { }
finally { connected = false; }
}
public boolean isConnected() {
return connected;
}
public int getPort(){
return port;
}
public void setPort(int port){
this.port = port;
}
public String getHostName(){
return hostName;
}
public void setHostName(String hostName){
this.hostName = hostName;
}
}