I am making an app that checks for certain connections (looking for a list of SSIDs) and creates an hotspot for said connection if it doesn't find any. Basically it should act as a local area network. I am successful in creating the hotspot, and after that it listens on a server socket for incoming connections:
Thread socketThread = new Thread(new Runnable() {
@Override
public void run() {
int port = Constants.PORT + socketList.size()-1;
try {
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(port);
Log.d(TAG, "Socket listening for connections: " + port);
Socket client = serverSocket.accept();
Log.d(TAG, "Server: connection done");
InputStream inputstream = client.getInputStream();
DataInputStream commStream = new DataInputStream(inputstream);
byte[] b = new byte[16];
while (commStream.read(b,0, 16) != -1)
Log.d(TAG, new String(b, "ASCII"));
serverSocket.close();
Log.d(TAG, "Server socket done");
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
});
socketList.add(socketThread);
socketThread.start();
If I create the hotspot and connect to it with my pc I am able to use netcat and connect with said socket:
netcat 192.168.43.1 8988
Where 192.168.43.1 is the default Android IP address for the hotspot and 8988 is the port I'm using. However, when I try to do the same through another device running the app and connecting to the hotspot, it doesn't work. Here's the client code:
clientThread = new Thread(new Runnable() {
@Override
public void run() {
int port = Constants.PORT ;
try {
Socket socket =new Socket();
socket.bind(null);
socket.connect((new InetSocketAddress("192.168.43.1", port)), 20000);
OutputStream stream = socket.getOutputStream();
DataOutputStream commStream = new DataOutputStream(stream);
commStream.write("1234567890123456".getBytes());
socket.close();
Log.d(TAG, "Client socket done");
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
});
clientThread.start();
It doesn't even connect to the server socket, it just waits until timeout. Is there anything I'm doing wrong here?
Thanks in advance.