集册 Java实例教程 使用套接字获取服务器状态

使用套接字获取服务器状态

欢马劈雪     最近更新时间:2020-01-02 10:19:05

547
使用套接字获取服务器状态

/** 
 来自 时代Java公众号**/

//package com.nowjava;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.net.InetSocketAddress;

import java.net.Socket;


public class Main {

    public static void main(String[] argv) throws Exception {

        String ip = "nowjava.com";

        int port = 2;

        System.out.println(getServerStatus(ip, port));

    }


    public static String getServerStatus(String ip, int port) {

        String c;

        String[] data = getServerData(ip, port);

        if (data[1].equals("Down.") && data[2].equals("Down.")) {

            c = "Down.";// from N o w J a v a . c o m

        } else {

            c = data[1] + "/" + data[2];

        }

        return c;

    }


    /**

     * Method for getting a server data

     *

     * @param ip   IP address of the target server.

     * @param port Port of the target server.

     *

     * @return Data given by the server.

     *

     * @author Master

     */

    public static String[] getServerData(String ip, int port) {

        String[] data;

        try {

            Socket socket = new Socket();

            socket.connect(new InetSocketAddress(ip, port), 5);

            DataOutputStream out = new DataOutputStream(

                    socket.getOutputStream());

            DataInputStream in = new DataInputStream(

                    socket.getInputStream());


            out.write(0xFE);


            StringBuilder sb = new StringBuilder();

            int b;

            while ((b = in.read()) != -1) {

                if (b != 0 && b > 16 && b != 255 && b != 23 && b != 24) {

                    
展开阅读全文