我试图编写一个Server Client程序,如果SERVER关闭或失去连接,将提示客户端。一旦我连接服务器和客户端然后断开它没有进入ConnectException
部分的服务器,会发生什么
示例:我打开了服务器和客户端连接,在客户端中它将显示"您已连接到服务器",然后如果服务器断开连接,则应该有一个"服务器已断开连接" 。当服务器重新打开时,它将提示客户端他已连接到服务器
如何连续检查服务器是打开还是断开连接
这是我的代码:
服务器
public class Server
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
System.out.println("Client has connected!");
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
客户端
public class Client
{
private static Socket socket;
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
System.out.println("Connected to the Server");
}
catch (ConnectException exception)
{
System.out.println("Server is still offline");
}
catch(IOException ex)
{
System.out.println("Server got disconnected");
}
}
}
答案 0 :(得分:-1)
那么,判断连接是否中断的最佳方法是尝试从套接字读取/写入。如果操作失败,那么您有时会丢失连接。
因此,您需要做的就是尝试在某个时间间隔读取,如果读取失败,请尝试重新连接。
对于您来说,重要的事件是当读取失败时 - 您丢失连接,并且当连接新套接字时 - 您重新获得连接。
通过这种方式,您可以跟踪正常运行时间和停机时间。
你可以这样做
try
{
Socket s = new Socket("address",port);
DataOutputStream os = new DataOutputStream(s.getOutputStream());
DataInputStream is = new DataInputStream(s.getInputStream());
while (true)
{
os.writeBytes("GET /index.html HTTP/1.0\n\n");
is.available();
Thread.sleep(1000);
}
}
catch (IOException e)
{
System.out.println("connection probably lost");
e.printStackTrace();
}
或者您可以像socket.setSoTimeout(timeout);
这样简单地连接超时以检查连接性
或者你可以使用
socket.getInputStream().read()
只要服务器连接,使线程等待输入,因此使你的程序不做任何事情 - 除非你得到一些输入和 如果客户端断开连接则返回-1 或者你能做的就是以这种方式构建你的代码
while(isConnected())
{
// do stuffs here
}