我试图通过套接字连接2台Android设备,但为什么它不起作用?我尝试用IP地址替换主机地址,但它没有成功。
服务器端(扩展AsyncTask):
ServerSocket server;
int port;
String hostName
server = new ServerSocket(0);
port = server.getLocalPort(); //is sent to client via OR code
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
hostName = inetAddress.getHostName(); //is sent to client via OR code
}
}
}
Socket client = server.accept();
客户端(扩展AsyncTask):
SocketAddress socketAddress = new InetSocketAddress(serverHostName, serverPort);
client = new Socket();
client.bind(null);
client.connect(socketAddress, SOCKET_TIMEOUT); //exception happens in this method
connected = true;
这是堆栈跟踪:
11-08 03:02:38.050: W/System.err(26424): java.net.SocketTimeoutException: failed to connect to /fe80::b652:7dff:feb5:ece2%wlan0%7 (port 54579) after 10000ms
11-08 03:02:38.090: W/System.err(26424): at libcore.io.IoBridge.connectErrno(IoBridge.java:150)
11-08 03:02:38.090: W/System.err(26424): at libcore.io.IoBridge.connect(IoBridge.java:112)
11-08 03:02:38.120: W/System.err(26424): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-08 03:02:38.160: W/System.err(26424): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
11-08 03:02:38.210: W/System.err(26424): at java.net.Socket.connect(Socket.java:848)
11-08 03:02:38.210: W/System.err(26424): at com.example.virtualcard.QRInternetClientThread.doInBackground(QRInternetClientThread.java:55)
11-08 03:02:38.220: W/System.err(26424): at android.os.AsyncTask$2.call(AsyncTask.java:264)
11-08 03:02:38.220: W/System.err(26424): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-08 03:02:38.220: W/System.err(26424): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-08 03:02:38.230: W/System.err(26424): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
11-08 03:02:38.230: W/System.err(26424): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-08 03:02:38.230: W/System.err(26424): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-08 03:02:38.230: W/System.err(26424): at java.lang.Thread.run(Thread.java:856)
答案 0 :(得分:0)
&#39; ave解决了我的问题。事实证明我应该在创建套接字之前在客户端上使用此代码,并且我不得不改变使用IP地址而不是主机名的东西。
InetAddress addr = InetAddress.getByName(serverIP);
SocketAddress socketAddress = new InetSocketAddress(addr, serverPort);
//here follows the old client code
SocketAddress socketAddress = new InetSocketAddress(serverHostName, serverPort);
client = new Socket();
client.bind(null);
client.connect(socketAddress, SOCKET_TIMEOUT); //exception happens in this method
connected = true;