Search code examples
javaandroidsocketsserversocketwifip2p

Unable to connect to other device via socket


I am working on a wireless file sharing app. I have created 2 different AsyncTasks, one for sending and one for receiving. In the class used for sending the data, Here is a snippet of the code I use for connecting.

client = new Socket();
client.bind(null);
client.connect(new InetSocketAddress(groupOwnerAddress, 8888));

In the class used for receiving the data, I create a ServerSocket and a Socket and then call

server = new ServerSocket(8888);
client = server.accept();

My devices aren't connecting to each other for some reason. In the device that I am sending the data from, I get the following message in the log.

I am pretty certain that my IP address is not wrong because I connected the 2 devices using WifiP2pManager's connect() method. I then got the IP address using by requesting the group information.

java.net.ConnectException: failed to connect to /192.168.49.1 (port 8888) from /:: (port 38275): connect failed: ECONNREFUSED (Connection refused)

The error points to this line

client.connect(new InetSocketAddress(groupOwnerAddress, 8888));

I looked up the error online and it said that the port is not listening.. But when i debug the receiving device, I can see that the debugger stops at this line

client = server.accept();

From what I can understand, this means that the device is listening on the port.

Any help is appreciated.


Solution

  • Make sure that the server socket (receiver) run first and then run the sender socket (sender) means makes the starting difference between sender and receiver for 5 to 8 second if you run the sender socket first and then start the server socket this connection failed error could be come.

    And sending the large file from java.io is not the good choice if you are using.Use the java.nio package for handling large file see this http://www.coderpanda.com/java-socket-programming-transferring-large-sized-files-through-socket/