我在Java中使用了套接字编程。我连接了一台电脑和安卓平板电脑。服务器是PC,客户端是平板电脑。当我首先启动平板电脑时,无法连接 socket 。但是,当我首先启动电脑时,套接字可以连接。为什么会这样呢?问题出在哪里?
电脑代码:
`
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
ServerSocket listener = null;
Socket socket = null;
System.out.println("Opened");
try {
listener = new ServerSocket(1515);
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
}
String answer = null;
while(true)
{
try {
socket = listener.accept();
DataInputStream input =
new DataInputStream(socket.getInputStream());
answer = input.readInt()+ " ";
answer = answer + input.readInt();
input.close();
dName.setText(answer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
t.start();
`
平板电脑代码:
@Override
public void run() {
// TODO Auto-generated method stub
boolean check = false;
while(!check)
{
try {
check = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, 2, 86 }).isReachable(1000);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while(!socket.isConnected()){
try {
socket.connect(sockaddr, 1000);
// DataInputStream input =
// new DataInputStream(socket.getInputStream());
// int result = input.readInt();
// if(result == -2)
// {
// MainActivity.MainAct.StartUpdateActivity();
// }
} catch (IOException e) {
// TODO Auto-generated catch block
//text.setText(e.getMessage());
System.out.println(e.getMessage());
}finally{
}
}
编辑:第一个 while ,使用 InetAddress.isReachable 的检查条件,始终为 TRUE。这意味着 isReachable 始终为 false。当我删除它时,可以建立连接。然而,问题仍然是一样的。
最佳答案
客户端套接字是连接到服务器的东西。
如果没有服务器在运行,则没有任何东西可供连接。
服务器套接字只接受连接。
关于java - 为什么服务器套接字要先于客户端套接字打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24005184/