java java简单服务器客户端程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25174072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:30:04  来源:igfitidea点击:

java Simple Server Client program

javasocketsnetwork-programming

提问by askManiac

I'm trying to build a simple server client program, I'm trying to figure a way how to prompt the CLIENT if the server is down, or if the server is up and loses connection

我正在尝试构建一个简单的服务器客户端程序,我正在尝试找出一种方法,如果服务器已关闭,或者服务器已启动并失去连接,则如何提示客户端

Question: How can I prompt the client that he's disconnected because the Server shuts down or loses connection

问题:如何提示客户端由于服务器关闭或失去连接而断开连接

SERVER

服务器

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();
    }
}

CLIENT

客户

public class Client{

private static Socket socket;

public static void main(String args[])
{
    Scanner input=new Scanner(System.in);
    while(true)
    {
        try
        {
            String host = "localhost";
            int port = 25000;
            InetAddress address = InetAddress.getByName(host);
            socket = new Socket(address, port);
            //System.out.println("You're now connected to the Server"); /*this should only print once */
            //Send the message to the server
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            String number;
            number=input.next();
            String sendMessage = number + "\n";
            bw.write(sendMessage);
            bw.flush();
            System.out.println("Message sent to the server : "+sendMessage);

            //Get the return message from the server
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String message = br.readLine();
            System.out.println("Message received from the server : " +message);
        }
        catch (IOException exception)
        {
            //System.out.println("Server is still offline");/*This should only print once*/
        }

回答by Rod_Algonquin

How can I prompt the client that he's disconnected because the Server shuts down or loses connection?

You can use the catch blockto prompt the client in Client class which will be executed when IOExceptionoccurs

您可以catch block在 Client 类中使用来提示客户端,该类将在IOException发生时执行

} catch (ConnectException e) { //When the connection is refused upon connecting to the server
      //promt the user here
      System.out.println("Connection refused");
      break; //to quit the infinite loop
} catch (IOException e) { //when connection drops, server closed, loses connection
     //promt the user here
     System.out.println("Disconnected from server");
     break; //to quit the infinite loop
}