ServerSocket accept() not accepting connections on Android

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-30 05:08:06

问题


I am trying to setup at ServerSocket on my Android phone, and send a char or int or anything from my computer.

The code on the phone creates a ServerSocket and then blocks whilst waiting for a connection:

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")

A simple bit of code running on my PC tries to connect to the phone:

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).

I have set the INTERNET permission on the phone. I have also been able to do this in reverse (ServerSocket on pc, client on phone).

Any ideas where I am going wrong?


回答1:


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. 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.



来源:https://stackoverflow.com/questions/4032482/serversocket-accept-not-accepting-connections-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!