我正在编写一个简单的套接字客户端-服务器应用程序,android 设备将是服务器,PC 是客户端。
在服务器端,像这样打开套接字:
Socket s = null;
try {
mServerSocket = new ServerSocket(6000);
Log.e("tag", getLocalIpAddress());
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = mServerSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
和客户端:
Socket socket;
try {
InetAddress serverAddr = InetAddress.getByName("10.0.2.2");
socket = new Socket(serverAddr, 6000);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println("Hello server");
System.out.println("Sent message to server");
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
运行服务器后,我已经运行客户端,它总是显示
> java.net.ConnectException: Connection timed out: connect
at java.net.TwoStacksPlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at main.main(main.java:19)
看起来客户端的IP地址不正确。但我不知道服务器的IP地址到底是什么!
注意:我使用的是真实设备,通过USB调试连接。
谢谢你。