1

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>
Community
  • 1
  • 1
  • As FD_ points out it won't go any further without an incoming connection. So how, and from what, are your attempting to initiate a connection to it? Also your summary of the second link it quite inaccurate, you really should re-read that one and understand it better. – Chris Stratton Jan 31 '14 at 19:53

2 Answers2

1

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.

A. Binzxxxxxx
  • 2,812
  • 1
  • 21
  • 33
0

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.

FD_
  • 12,947
  • 4
  • 35
  • 62