views:

175

answers:

2

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(); 
} 
A: 

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 );
}
Nikolai N Fetissov
And accept it into a separate thread so it can perform its work asynchronously rather than one at a time.
Brad Hein
Sigh ... it doesn't have to be threads. Only pay for what you need.
Nikolai N Fetissov
A: 

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();
}
Brad Hein