user3254705
user3254705

Reputation: 15

Android not getting past serverSocket.accept();

I am currently trying to open a socket in android, but my code keeps sticking at one sentence.

  private ServerSocket serverSocket;
  private Socket clientSocket;
  private PrintWriter out;
  private BufferedReader in;

  public void run(){
    Log.i("DebugMessage", "ServerThread received pulse. Trying to open socket now!");
    try{
      serverSocket = new ServerSocket(25555);
      Log.i("DebugMessage", "serverSocket is open, waiting for the clientSocket.");
      clientSocket = serverSocket.accept();
      Log.i("DebugMessage", "serverSocket and clientSocket are both open! Waiting for in-/output!");

      in = new BufferedReader(
             new InputStreamReader(clientSocket.getInputStream()));
      out = new PrintWriter(clientSocket.getOutputStream(), true);

      String input = in.readLine();
      out.println("received: " + input);

      in.close();
      out.close();

    } catch(Exception e) {
        Log.i("DebugMessage", "Failed to open socket!");
    e.printStackTrace();
    }
  }

At clientSocket = serverSocket.accept(); it keeps sticking. Now I have seen this question a few other times, but the answers given were totally different. Here is being said that it is about his code, and here is being said that the problem is with the emulator. Now my question is, is my problem with the emulator or my code, and if it is with my code, how is it possible to fix it?

By the way, I have added these lines to AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>

Upvotes: 1

Views: 2292

Answers (2)

A. Binzxxxxxx
A. Binzxxxxxx

Reputation: 2871

The answer of FD_ is correct but i want to clarify it a bit. accept() calls wait(). So the thread will wait for a connection. You may want to call such code from a other thread.

Upvotes: 1

FD_
FD_

Reputation: 12919

ServerSocket.accept() waits until a device connects to the socket's port (25555 in your case) on your device's ip address. It will only proceed and return a Socket when there is a new connection.

You'll find more information in the docs.

Upvotes: 0

Related Questions