我有 2 台 android 设备,一台充当服务器,处于网络共享模式,并接受与端口的连接。另一台设备充当客户端,连接到服务器热点并通过端口与服务器建立连接。(一切都是在中间没有路由器的情况下完成的)。
服务器代码如下所示:(当android服务器执行代码时,设备处于tethering模式)
ServerSocket server = new ServerSocket(PORT);
while (true) {
Socket client;
client = server.accept();
ClientThread com = new ClientThread(client, this);
Thread t = new Thread(com);
t.start();
}
客户端代码如下所示:(当android客户端执行此代码时,设备连接到接入点)
Socket client = new Socket();
int serverIP = wifiManager.getDhcpInfo().serverAddress;
String stringIP = android.text.format.Formatter.formatIpAddress(serverIP);
InetAddress address = InetAddress.getByName(stringIP);
SocketAddress socketAddress = new InetSocketAddress(address, PORT);
client.connect(socketAddress);
我在客户端收到以下错误
java.net.ConnectException: failed to connect to /192.168.43.1 (port 12345): connect failed: ENETUNREACH (Network is unreachable)
at libcore.io.IoBridge.connect(IoBridge.java:114)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:842)
at java.net.Socket.connect(Socket.java:785)
at com.alternatewifimeshmessaging.HostManager.clientConnect(HostManager.java:283)
at com.alternatewifimeshmessaging.HostManager.client(HostManager.java:189)
at com.alternatewifimeshmessaging.HostManager.run(HostManager.java:59)
at java.lang.Thread.run(Thread.java:856)
Caused by: libcore.io.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
at libcore.io.Posix.connect(Native Method)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
... 8 more
服务器没有给出错误。
我在 android 清单文件中设置了以下权限:
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
理想情况下,我需要将一些数据从服务器传输到客户端。
我究竟做错了什么?