问题
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