简体   繁体   English

Java Socket编程服务器客户端

[英]java Socket programming Server Client

I'm trying to program a Server Client program where the CLIENT will be prompt if the SERVER closes or loses connection. 我正在尝试编写服务器客户端程序,如果SERVER关闭或失去连接,将在其中提示CLIENT。 What happens is once I connect the server and the client then disconnects the server it doesn't go to the ConnectException part example: I opened the Server and Client connects, in the Client it will show that "You are connected to the Server", then if the Server disconnects there should be a "Server is disconnected". 发生的事情是,一旦我连接了服务器和客户端,然后断开了服务器的连接,它就不会进入ConnectException部分示例:我打开了Server和Client的连接,在Client中它将显示“您已连接到服务器”,那么如果服务器断开连接,则应该有一个“服务器断开连接”。 and when the Server reopens it will prompt the Client that he's connected to the Server 当服务器重新打开时,它将提示客户端他已连接到服务器

How can I continuously check if the Server is open or disconnected 如何连续检查服务器是否打开或断开连接

here's my code: 这是我的代码:

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

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

Well, the best way to tell if your connection is interrupted is to try to read/write from the socket. 好吧,判断您的连接是否中断的最佳方法是尝试从套接字读取/写入。 If the operation fails, then you have lost your connection sometime. 如果操作失败,则说明您有时失去了连接。

So, all you need to do is to try reading at some interval, and if the read fails try reconnecting. 因此,您需要做的是尝试以一定的时间间隔读取,如果读取失败,请尝试重新连接。

The important events for you will be when a read fails - you lost connection, and when a new socket is connected - you regained connection. 对于您来说,重要的事件将是读取失败时(连接断开)和新套接字连接时(重新获得连接)。

That way you can keep track of up time and down time. 这样,您可以跟踪正常运行时间和停机时间。

you can do like this 你可以这样

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

or you can simply et connection time out like this socket.setSoTimeout(timeout); 或者您也可以像这个socket.setSoTimeout(timeout);那样简单地设置连接socket.setSoTimeout(timeout); to check connectivity or you can use 检查连接性,或者您可以使用

socket.getInputStream().read()

makes the thread wait for input as long as the server is connected and therefore makes your program not do anything - except if you get some input and returns -1 if the client disconnected or what you can do is structure your code in this way 使线程在服务器连接后一直等待输入,因此使您的程序不执行任何操作-除非您获得一些输入,并且如果客户端断开连接则返回-1或可以通过这种方式构造代码

while(isConnected())
  {
      // do stuffs here
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM