1

現在の接続で接続が拒否された場合、または現在の IP が存在しない場合は、別の IP に切り替える必要があります。コードの一部を次に示します。

String [] server= {"10.201.30.200", "10.66.20.70",}; // Servers array

public void Telnet(String[] server) {
    try {
        out2 = new PrintStream(new FileOutputStream("output.txt"));
        String [] hrnc = {"HRNC01_", "HRNC02_", "HRNC03_","NRNC01_", "NRNC02_"};

        for (int i = 0; i < server.length; i++) {        
            // Connect to the specified server
            if (server[i].equals("10.201.30.200")) { 
                // Commands via telnet
            } else if (server[i].equals("10.66.20.70")) {
                // Commands
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}    

たとえば、最初の IP が存在しない場合、次のサーバーに接続する必要があります。

4

2 に答える 2

1

各接続試行を try/catch ステートメントに入れてみてください

于 2012-10-23T10:25:43.400 に答える
1

接続を試み、例外をキャプチャし、発生した場合は別の IP アドレスを試してください。

編集:もちろん!これは私の実装です

package tests;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

public class Connection {
    // Servers array
    private static final String[] server = { "10.201.30.200", "10.66.20.70" };
    // @logoff: default Telnet port
    private static final int port = 23;

    public static void telnet(String[] server) {
        PrintStream out2;
        try {

            out2 = new PrintStream(new FileOutputStream("output.txt"));

            String[] hrnc = { "HRNC01_", "HRNC02_", "HRNC03_", "NRNC01_",
                    "NRNC02_" };

            for (int i = 0; i < server.length; i++) {
                try {
                    // @logoff: try connection
                    Socket socket = new Socket(server[i], port);
                } catch (IOException e) {
                    // @logoff: typical "Connection timed out" or
                    // "Connection refused"
                    System.err.println("Error connecting to " + server[i]
                            + ". Error = " + e.getMessage());
                    // @logoff: continue to next for element
                    continue;
                }

                // Connect to the specified server
                if (server[i].equals("10.201.30.200")) {
                    // Commands via telnet
                }

                else if (server[i].equals("10.66.20.70")) {
                    // Commands
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // @logoff: your method returns void
        return;
    }

    public static void main(String[] args) {
        telnet(server);
    }
}
于 2012-10-23T10:20:48.440 に答える