[英]How to open port in Android?
How can I open a specific port in android? 如何在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). 如果您仍然无法使用它,我建议您创建一个扩展Thread的内部类,以替换整个
new Thread() {
... }.start()
语句(我一直很难将它们转换为当我尝试声明实例字段时,它的工作完全正确,我只是坚持使用这种声明来创建/覆盖方法。 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);
我将使内部类(例如
ClientAnsweringThread
)具有一个将Socket( client
)作为参数,然后调用ProcessClientRequest(_client);
in the run()
method as you already have. 就像在
run()
方法中一样。
It looks that you are just missing a loop around the accept()
call so you can accept multiple connections. 看来您只是在
accept()
调用周围缺少了一个循环,所以您可以接受多个连接。 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.