Steven Combs
Steven Combs

Reputation: 1939

How do I open up a ServerSocket in my android application?

Ok so I am doing something that seems like it should be very easy. I am basically trying to open up a ServerSocket connection and then wait for the client to connect.

Here is my code.

ServerSocket serverSocket = new ServerSocket(6543);
Socket clientSocket = serverSocket.accept();

Whenever my code hits, serverSocket.accept();, I am throwing the following exception.

bind failed: EADDRINUSE (Address already in use)

So obviously my next step was to check and see if another port would work, it did not. Next I restarted the device and tried running the app and I got the same exception. I have given my app INTERNET permission and the device is rooted.

Here are my network interfaces that show up.

lo: ::1%1
lo: 127.0.0.1
eth0: //IPV6 address 
eth0: 192.168.1.127

EDIT 1

Here is the serverSocket object info that I get when debugging.

ServerSocket[addr=192.168.1.121/192.168.1.121,port=0,localport=1234]

EDIT 2

I have the following available constructors in my ServerSocket

new ServerSocket(int port)
new ServerSocket(int port, int backlog)
new ServerSocket(int port, int backlog, InetAddress localAddress)

I tried using the 3rd constructor and same exception.

new ServerSocket(4567, 0, InetAddress.getLocalHost());

Upvotes: 3

Views: 1816

Answers (1)

Steven Combs
Steven Combs

Reputation: 1939

Alright so I finally figured out why my application was throwing an exception and if anyone has some feedback on this or would like to provide an answer as to why this was happening. I would greatly appreciate it.

So in my Thread that I created I need to postback to the main thread to update some TextView's based upon what was happening with the server connection. Well since I can't update the main thread from my self created thread I needed to add a Handler object to that Thread in order to update the UI. Removing that Handler completely allowed my application to successfully create the ServerSocket without throwing an exception.

Does the Handler somehow run the code before hand or what was happening here?

The code.

RemoteServerRunnable test = new RemoteServerRunnable();
Handler handler = new Handler();
handler.post(test);
test.start();

Upvotes: 1

Related Questions