【发布时间】:2015-02-01 02:24:00
【问题描述】:
我正在尝试设置一个客户端-服务器系统,其中 Pi 作为服务器,Android 设备作为客户端。每次我运行代码(我从互联网上拼凑)时,客户端都会抛出一个 IOException:
Connection timed out: connect
我刚刚发现,当我尝试 ping Pi 的 IP 时,它无法访问。 我该如何解决这个问题?
请注意,我目前正在 Windows PC 上测试 Java 代码,直到它可以工作为止。
客户端代码(Java):
import java.io.*;
import java.net.*;
public class client
{
static Socket clientSocket;
static String homeIp="192.168.0.105"; //internal ip of server (aka Pi in this case)
static int port=4242;
public static void main(String [] args)
{
sendToPi("I sent a message");
}
public static void sendToPi(String s)
{
//wordsList.append("in sendToPi()\n");
System.out.println("in sendToPi()");
//Log.e("aaa","in sendToPi()\n");
try {
clientSocket = new Socket(homeIp, port);
PrintStream out = new PrintStream(clientSocket.getOutputStream());
out.println(s);
} catch (UnknownHostException e) {
//Log.e("aaa","Don't know about host: "+homeIp+"."+e.getMessage());
System.out.println("Don't know about host: "+homeIp+"."+e.getMessage());
//System.exit(1);
} catch (IOException e) {
//Log.e("aaa","Couldn't get I/O for the connection to: "+homeIp+"."+e.getMessage());
System.out.println("Couldn't get I/O for the connection to: "+homeIp+"."+e.getMessage());
//System.exit(1);
}
}
}
服务器代码 (C):我使用了来自 here 的代码,与所写的完全相同。编译为服务器。从 ./server 4242 开始
【问题讨论】:
-
谢谢,已解决。知道为什么它不起作用吗?
-
static String homeIp="localhost";- 您需要提供树莓派设备的 ip。使用您当前的代码,Android 设备正在尝试连接到同一部手机上的 4242 端口。
标签: java android c++ client-server