Ricardo
Ricardo

Reputation: 71

How to open port in Android?

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

Upvotes: 3

Views: 11882

Answers (3)

Ian
Ian

Reputation: 11

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.

Upvotes: 1

Brad Hein
Brad Hein

Reputation: 11047

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

Upvotes: 0

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84169

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 );
}

Upvotes: 0

Related Questions