I'm trying to write an app that connects to a local server. I wrote the server side in JAVA, and I ran it with a client I implemented in JAVA. Im trying now to connect to the server through the app, i.e. with my anrdroid device, but for some reason I get an error.
Im using sockets, and this is what I'm trying to do (remember that it worked with a JAVA file):
String hostName = "localhost";
int portNumber = 5667;
private Socket echoSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
echoSocket = new Socket(hostName, portNumber);
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to "
+ hostName);
System.exit(1);
}
I ran the server on my computer through local host. Any idea why I get the error?
EDIT:
I can't get the socket to work. Let's put aside the UI for a moment. I found many posts about socket communication but I still cant get it to work. I wrote a server side in JAVA and ran it on some arbitrary port, and now I want my device to communicate with the server on local host. That's what I tried to do:
public class MainActivity extends Activity {
String hostName = "10.0.0.1";
int portNumber = 5667;
private Socket echoSocket;
private void runSecondThread() {
new Thread() {
@Override
public void run() {
try {
Log.i("try", "enter try");
InetAddress serverAddr = InetAddress.getByName(hostName);
Log.i("try", "InetAddress");
echoSocket = new Socket(serverAddr, portNumber);
Log.i("taggg", "echoSocket");
} catch (UnknownHostException e) {
Log.i("error","Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
Log.i("error","Couldn't get I/O for the connection to "+ hostName);
System.exit(1);
}
}
}.start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runSecondThread();
}
I get in the log "enter try" and "InetAddress", but not "echo socket". I dont get any exception so I really dont know what I did wrong.