我在Java中使用了套接字编程。我连接了一台PC和android平板电脑。服务器是PC,客户端是平板电脑。当我首先启动平板电脑时,无法连接插座。但是,当我首先启动pc时,可以连接套接字。为什么会这样呢?问题出在哪儿 ?
邮递区号:
`
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{
}
}
编辑:在使用InetAddress.isReachable进行检查时,始终为TRUE。这意味着isReachable始终为false。当我删除它时,可以建立连接。但是,问题仍然是相同的。
检查文档isConnected
:套接字
Returns the connection state of the socket.
Note: Closing a socket doesn't clear its connection state, which means this method will return true for a closed socket (see isClosed()) if it was successfuly connected prior to being closed.
所以你
while(!socket.isConnected()){
线路仅在首次成功连接之前有效。
更新
似乎EJP的答案也是如此,即使您的while(!socket.isConnected()){
工作正常,也无法使用已经关闭的套接字建立连接,但最终还是会发生java.net.SocketException: Socket closed
。因此,您必须每次都重新创建套接字。
while (!shouldIStop()/*some condition in case if you ever want to stop*/) {
Socket socket = new Socket();
try {
socket.connect(yourAddress, 1000);
//do something...
} catch (IOException e) {
} finally {
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句