Java examples for Network:Socket
get Server Status using Socket
//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(getServerStatus(ip, port)); }// w w w . j a va2s .co m 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."; } 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) { sb.append((char) b); } } data = sb.toString().split("?"); socket.close(); } catch (Exception e) { data = new String[] { "Server down.", "Down.", "Down." }; } return data; } }