socketプログラミング、簡単な表示

1672 ワード

会社のネットは力がないですね.
仕方なく、ネットが正常な時にいくつかの資料を調べて、ついでにsocketを復習するしかありません!
public static void main(String[] args) {
    	/**
    	 *  
    	 * <p>
    	 * 1. Ip , 
    	 * 2. , 
    	 * 3. , 
    	 * </p>
    	 */
    	String host = "";
    	int port=80;
		Scanner sc = new Scanner(System.in);
		
		boolean flag =true;
		while (flag) {
			System.out.println(" ");
			host=sc.next();
			System.out.println(" ");
			port=Integer.parseInt(sc.next());
			new SocketDemo().connect(host, port);
			System.out.println(" , T, F");
			if (sc.next().equals("T")) {
				continue ;
			}else{
				System.out.println(" !");
		        break;
			}
			
		}
		
		
	}
    public void connect(String host,int port){
    	SocketAddress remoteAddr=new InetSocketAddress(host,port);
    	Socket socket = null;
    	String result="";
    	
    	try {
    		long begin=System.currentTimeMillis();
        	socket = new Socket();
			socket.connect(remoteAddr, 10000);
			long end = System.currentTimeMillis();
			result =" ,   "+ (end-begin)+"ms";
		} catch (BindException e) {
			result="local address and port cant bind";
		}catch (UnknownHostException e) {
			result="Unknow Host";
		}catch (ConnectException e) {
			result="Connect Refused";
		}catch (SocketTimeoutException e) {
			result="TimeOut";
		}catch (IOException e) {
			result="failure";
		}finally{
			if (socket!=null)
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
    	System.out.println(remoteAddr+":"+result);
    	
    	
    }