Java 如何让客户端套接字等待服务器套接字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18616740/
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-08-12 09:33:56  来源:igfitidea点击:

How to make client socket wait for server socket

javasockets

提问by qweruiop

If client socket opens before the server socket, Java will generate a ConnectionException. So I have to check whether the server is available and keep waiting before executing

如果客户端套接字在服务器套接字之前打开,Java 将生成一个ConnectionException。所以我必须检查服务器是否可用并在执行之前保持等待

socketChannel.open(hostname, port)

socketChannel.open(hostname, port)

in client thread. I've found an related API:

在客户端线程中。我找到了一个相关的API:

InetAddress.getByName(hostname).isReachable()

InetAddress.getByName(hostname).isReachable()

However, this still can't tell whether the socket on a specific portis open. I think this problem should be common but I didn't get very useful information from Google and other places.

但是,这仍然无法判断特定端口上的套接字是否打开。我认为这个问题应该很普遍,但我没有从谷歌和其他地方得到非常有用的信息。

采纳答案by Cruncher

boolean scanning=true;
while(scanning)
{
    try
    {
        socketChannel.open(hostname, port);
        scanning=false;
    }
    catch(ConnectionException e)
    {
        System.out.println("Connect failed, waiting and trying again");
        try
        {
            Thread.sleep(2000);//2 seconds
        }
        catch(InterruptedException ie){
            ie.printStackTrace();
        }
    } 
}

This is the code for sonics comment

这是sonics评论的代码

回答by Gianmarco

I Will give this kind of handler for your client, I am using it in my little game.

我将为您的客户提供这种处理程序,我正在我的小游戏中使用它。

It will also give up after few times.

几次后它也会放弃。

private static int MAX_CONNECTION = 10;
private int reconnections = 0;

public void connect() {

            try {
                    this.socket = new Socket();
                    InetSocketAddress sa = new InetSocketAddress(this.server, this.port);
                    this.socket.connect(sa,500);
                    this.connected = true;

                    this.in = new InputStreamReader(this.socket.getInputStream());
                    this.out = new OutputStreamWriter(this.socket.getOutputStream());
            } catch (ConnectException e) {
                    System.out.println("Error while connecting. " + e.getMessage());
                    this.tryToReconnect();
            } catch (SocketTimeoutException e) {
                    System.out.println("Connection: " + e.getMessage() + ".");
                    this.tryToReconnect();
            } catch (IOException e) {
                    e.printStackTrace();
            }

    }
private void tryToReconnect() {
            this.disconnect();

            System.out.println("I will try to reconnect in 10 seconds... (" + this.reconnections + "/10)");
            try {
                    Thread.sleep(10000); //milliseconds
            } catch (InterruptedException e) {
            }

            if (this.reconnections < MAX_RECONNECTIONS) {
                    this.reconnections++;
                    this.connect();

            } else {
                    System.out.println("Reconnection failed, exeeded max reconnection tries. Shutting down.");
                    this.disconnect();
                    System.exit(0);
                    return;
            }

    }

Here is the explanation of the code:

下面是代码的解释:

private static final int MAX_CONNECTION = 10;
private int reconnections = 0;

First I declare two vars, one is fixed and cannot be changed at runtime, it's the maximum number of attempt I want the client to do before shutting down. The second is the current reconnection attempt.

首先我声明了两个变量,一个是固定的,不能在运行时更改,这是我希望客户端在关闭之前进行的最大尝试次数。第二个是当前的重新连接尝试。

public method connect() is used to connect the socket. I will skip to the exception handling:

公共方法 connect() 用于连接套接字。我将跳到异常处理:

} catch (ConnectException e) {
    System.out.println("Error while connecting. " + e.getMessage());
    this.tryToReconnect();
} catch (SocketTimeoutException e) {
    System.out.println("Connection: " + e.getMessage() + ".");
    this.tryToReconnect();
}

When a connection exception is thrown the catcher call the reconnection method.

当抛出连接异常时,捕获器调用重新连接方法。

The reconnection method wait 10 second between each attempt and is called each time by connect() if this fail.

重新连接方法在每次尝试之间等待 10 秒,如果失败,则每次由 connect() 调用。

If the connection is established connect() will not call tryToReconnect() again. If is impossible to connect within 100 seconds 10 attempts one every 10 second, the program exit.

如果连接建立,connect() 将不会再次调用 tryToReconnect()。如果在 100 秒内无法连接 10 次每 10 秒尝试一次,则程序退出。