Method for getting a server data via Socket - Java Network

Java examples for Network:Socket

Description

Method for getting a server data via Socket

Demo Code


//package com.java2s;
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 = "java2s.com";
        int port = 2;
        System.out.println(java.util.Arrays
                .toString(getServerData(ip, port)));
    }//from   ww w. j a va2  s .c o  m

    /**
     * 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) {
                    sb.append((char) b);
                }
            }

            data = sb.toString().split("?");
            socket.close();
        } catch (Exception e) {
            data = new String[] { "Server down.", "Down.", "Down." };
        }
        return data;
    }
}

Related Tutorials