Can't use ServerSocket on Android Can't use ServerSocket on Android android android

Can't use ServerSocket on Android


Instead of using server.bind, try initializing the server socket like this:server = new ServerSocket(4040);

Also, server.accept() will actually block until a connection is made, so you don't need that while loop (see: http://download.oracle.com/javase/1.5.0/docs/api/java/net/ServerSocket.html#accept() )


I struggled with this too and was only able to connect to my Android server by using:

ServerSocket myServerSocket = new ServerSocket();String hostname = getLocalIpAddress();myServerSocket.bind(new InetSocketAddress(hostname, myPort));

Where hostname was the local IP, which I got using the getLocalIpAddress() function from this page:

https://github.com/Teaonly/android-eye/blob/master/src/teaonly/droideye/MainActivity.java


I was able to get this working by using

 ServerSocket server = new ServerSocket( myTcpPort, 0, addr );

where addr = InetAddress of your phone. Otherwise, it only seems to bind to localhost (127.0.0.1). Also, I'm using port 8080.