简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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