Tutorial :How to open port in Android?



Question:

How can I open a specific port in android?

I have a server socket but the connection is rejected because the port is closed.

try {     ServerSocket server = new ServerSocket(2021);     Socket client = server.accept();   } catch (Exception e) {     // TODO Auto-generated catch block     a = false;     e.printStackTrace();   }   


Solution:1

If you still havn't got it to work, I would suggest that you create an inner class that extends Thread to replace that whole new Thread() {...}.start() statement (I have always had trouble getting those to work exactly right when I try to declare an instance field, I just stick with creating/overriding methods in that kind of statement). I would make the inner class, say ClientAnsweringThread, have a constructor that takes in the Socket (client) as a parameter and then calls ProcessClientRequest(_client); in the run() method as you already have.


Solution:2

It looks that you are just missing a loop around the accept() call so you can accept multiple connections. Something like this:

ServerSocket server = new ServerSocket( port );    while ( true )  {      Socket client = server.accept();      ProcessClientRequest( client );  }  


Solution:3

To illustrate what I meant in my comment:

ServerSocket server = new ServerSocket( port );  while ( true )  {      Socket client = server.accept();      new Thread () {           final Socket _client = client;          // This stuff runs in a separate thread all by itself          public void run () {              ProcessClientRequest(_client);          }      }.start();  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »