集册 Java实例教程 通过Socket获取服务器数据的方法

通过Socket获取服务器数据的方法

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

618
通过Socket获取服务器数据的方法


//package com.nowjava;/**来 自 n o w  j a v a  . c o m**/

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(java.util.Arrays

                .toString(getServerData(ip, port)));//from 时代Java - nowjava.com

    }


    /**

     * 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);

                }

            }


展开阅读全文