我正在制作一个应用程序来检查某些连接(查找 SSID 列表)并在找不到任何连接时为所述连接创建一个热点。基本上它应该充当局域网。我成功创建了热点,然后它在服务器套接字上侦听传入连接:
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();
如果我创建热点并用我的电脑连接到它,我可以使用 netcat 并连接到所述套接字:
netcat 192.168.43.1 8988
其中 192.168.43.1 是热点的默认 Android IP 地址,而 8988 是我正在使用的端口。但是,当我尝试通过另一台运行该应用程序并连接到热点的设备执行相同操作时,它不起作用。这是客户端代码:
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();
它甚至不连接到服务器套接字,它只是等到超时。我在这里做错了什么吗?
提前致谢。