Can't open Java Server Socket on Android

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Can't open Java Server Socket on Android



I'm trying to program a simple Android chat program. For testing I want to have the server and the client running on the same device. I'm currently stuck with the very first step of setting up the server part and I simply don't know what I'm doing wrong. (The server will late be run in an own thread)


public class MainActivity extends AppCompatActivity

@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

int port = 4444;

try
ServerSocket serverSocket = new ServerSocket(port);
Log.i("Info", "Server socket initiated on port" + port);

catch (IOException e)
Log.e("Error", "Could not listen on port " + port);





I tried lots of different ports but I still get the IO Error. I also tried to simply use new ServerSocket(0) to allocate a free port using the following code:


public class MainActivity extends AppCompatActivity

@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ServerSocket serverSocket = null;

try
serverSocket = new ServerSocket(0);
Log.i("Info", "Server socket initiated on port" + serverSocket.getLocalPort());

catch (IOException e)
Log.e("Error", "Could not listen on port " + serverSocket.getLocalPort());





But this simply returs a port number of -1 which means the serversocket still isn't bound to anything.





You might need to state that your application requires network access.
– npinti
Aug 6 at 10:18





I added the permission <uses-permission android:name="android.permission.INTERNET" /> in the manifest and I still get -1
– Stephan Pillhofer
Aug 6 at 10:24






get the IO Error which one? where is the stacktrace?
– Vladyslav Matviienko
Aug 6 at 10:26


get the IO Error





ok, I'm sorry I dunno why but adding the permission now fixed the problem. Suddenly it's working. Thx npinit!
– Stephan Pillhofer
Aug 6 at 10:36




1 Answer
1



The answer was to add the permission in the manifest. Thx!






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered