我有一个服务器套接字在我的本地计算机上监听,我正在尝试从我的安卓手机连接到它。 我已经在同一台计算机上用客户端测试了服务器套接字,它们能够连接。
但是,我的 Android 手机客户端无法连接到套接字。 我的计算机的防火墙已关闭。我的电脑和手机都连接到同一个wifi网络。有人可以帮忙吗?
客户端套接字代码如下:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread fst = new Thread(new startConnection());
fst.start();
}
public class startConnection implements Runnable {
public void run() {
try {
final InetAddress hostAddr = InetAddress.getByName("192.168.2.1");//This is the local IP of my computer where the serversocket is listening
clientSocket = new Socket();
clientSocket.bind(null);
clientSocket.connect(new InetSocketAddress(hostAddr, 12555),30000);
} catch (Exception e) {
e.printStackTrace();
} // end TryCatch block
}
}
我不断收到的错误是套接字连接超时。求助?
非常感谢!
最佳答案
发现问题。 我正在使用这段代码来获取服务器的本地 IP:
try {
ip = InetAddress.getLocalHost();
}catch (UnknownHostException e) {
e.printStackTrace();
}
这为服务器的本地 IP 提供了类似 192.168.2.1 的内容。然后我使用这个地址将客户端连接到服务器,但连接从未成功。
我不得不改用像 10.0.0.9 这样的数字,然后它就起作用了。 为了获得正确的 IP,我必须使用以下代码:
Enumeration<NetworkInterface> nis = null;
try {
nis = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
NetworkInterface ni;
while (nis.hasMoreElements()) {
ni = nis.nextElement();
try {
if (!ni.isLoopback() && ni.isUp()) {
for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
//filter for ipv4/ipv6
if (ia.getAddress().getAddress().length == 4) {
//4 for ipv4, 16 for ipv6
System.out.println(ia.getAddress());
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这给了我: /10.0.0.9 /192.168.2.1
第一个数字是正确的。
有人可以从网络的角度解释一下,这两个数字/获取它们的代码有什么区别以及为什么一个有效?
谢谢!
关于java - Android客户端套接字无法连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20113245/