如何在Android中打开端口?

发布于 2024-09-12 20:28:44 字数 282 浏览 5 评论 0原文

如何在android中打开特定端口?

我有一个服务器套接字,但连接被拒绝,因为端口已关闭。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

っ左 2024-09-19 20:28:44

如果您仍然无法正常工作,我建议您创建一个扩展 Thread 的内部类来替换整个 new Thread() {...}.start() 语句(当我尝试声明实例字段时,我总是很难让它们完全正确地工作,我只是坚持在这种语句中创建/重写方法)。我将使内部类(例如 ClientAnsweringThread)具有一个构造函数,该构造函数接受 Socket (client) 作为参数,然后调用 ProcessClientRequest(_client);< /code> 在 run() 方法中,就像您已经拥有的那样。

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.

痴意少年 2024-09-19 20:28:44

看起来您只是缺少一个围绕 accept() 调用的循环,因此您可以接受多个连接。像这样的事情:

ServerSocket server = new ServerSocket( port );

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

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 );
}
鹿港巷口少年归 2024-09-19 20:28:44

为了说明我在评论中的意思:

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

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文