简体   繁体   English

ServerSocket accept() 不接受 Android 上的连接

[英]ServerSocket accept() not accepting connections on Android

I am trying to setup at ServerSocket on my Android phone, and send a char or int or anything from my computer.我正在尝试在我的 Android 手机上的 ServerSocket 上进行设置,并从我的计算机发送一个字符或整数或任何内容。

The code on the phone creates a ServerSocket and then blocks whilst waiting for a connection:手机上的代码创建了一个 ServerSocket,然后在等待连接时阻塞:

ServerSocket serverSocket = ServerSocketFactory.getDefault()
                            .createServerSocket(4444);
Log.d("HostThread", "ServerSocket created:"+serverSocket
                             .getInetAddress().getHostAddress());
Socket socket = serverSocket.accept();

(The log says "10-27 11:41:43.437: DEBUG/HostThread(23957): ServerSocket created:0.0.0.0") (日志说“10-27 11:41:43.437: DEBUG/HostThread(23957): ServerSocket created:0.0.0.0”)

A simple bit of code running on my PC tries to connect to the phone:在我的 PC 上运行的一段简单代码尝试连接到手机:

Socket s = new Socket("xx.xx.xx.xx", 4444);

... (plus some more bits if the socket is created. But I'm not getting this point, so left that out!) ...(如果创建了套接字,再加上一些位。但我不明白这一点,所以忽略了这一点!)

Basically, the phone is getting to accept, and the computer is not connecting.基本上,手机正在接受,而计算机无法连接。 The xx.xx.xx.xx is the public IP of the phone I obtain programatically (and it matches up with checking on whatismyip.com). xx.xx.xx.xx 是我以编程方式获得的电话的公共 IP(它与检查 whatismyip.com 相匹配)。

I have set the INTERNET permission on the phone.我已经在手机上设置了 INTERNET 权限。 I have also been able to do this in reverse (ServerSocket on pc, client on phone).我也能够反向执行此操作(PC 上的 ServerSocket,电话上的客户端)。

Any ideas where I am going wrong?我哪里出错了?

Are you running this in the emulator or on a real device?您是在模拟器中还是在真实设备上运行它? As far as I understand, most operators networks are NATed and doesn't allow connections to devices.据我了解,大多数运营商网络都经过 NAT 处理,不允许连接到设备。 This may be your problem, if you're running on a real device.如果您在真实设备上运行,这可能是您的问题。

However, if your code above is just an example - and you actually don't use port 4444, you should also be aware of that most unix systems (including Android) won't allow incoming connections on ports lower than 1024, unless you have root permissions.但是,如果您上面的代码只是一个示例——并且您实际上不使用端口 4444,那么您还应该意识到大多数 unix 系统(包括 Android)将不允许低于 1024 的端口上的传入连接,除非您有根权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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