简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM