1 import java.net.*; 2 import java.io.*; 3 4 5 6 public class Echo implements Runnable { 7 8 private int port; 9 private InetAddress peerIp; 10 11 private Socket ss; 12 private InputStream in; 13 private OutputStream out; 14 15 private static final int BUF_SIZE = 1024; 16 17 18 public Echo(String host,int port,String peerHost,int peerPort) 19 throws IOException,UnknownHostException{ 20 this.peerIp = InetAddress.getByName(peerHost); 21 this.port = port; 22 23 ss = new Socket(host, port,peerIp,peerPort); 24 out = ss.getOutputStream(); 25 in = ss.getInputStream(); 26 System.out.println("Connected..."); 27 System.out.println("TO: "+host+":"+port); 28 System.out.println("LocalAddress: "+ss.getLocalAddress().getHostAddress() 29 +":"+ss.getLocalPort()); 30 31 } 32 public Echo(String host,int port) 33 throws IOException,UnknownHostException{ 34 35 System.out.println("Connecting..."); 36 ss = new Socket(host, port); 37 out = ss.getOutputStream(); 38 in = ss.getInputStream(); 39 System.out.println("TO: "+host+":"+port); 40 System.out.println("LocalAddress: "+ss.getLocalAddress().getHostAddress() 41 +":"+ss.getLocalPort()); 42 43 } 44 45 46 public void send(String s) throws IOException{ 47 out.write(s.getBytes()); 49 } 50 51 public void run(){ 52 byte[] buf = new byte[1024]; 53 int bytes_read; 54 try{ 55 while((bytes_read = in.read(buf)) > 0){ 56 System.out.write(buf,0,bytes_read); 57 System.out.flush(); 58 } 59 }catch(IOException io_ex){ 60 io_ex.printStackTrace(); 61 } 62 } 63 64 public static void usage(){ 65 System.err.print( 66 "Usage: java Echo host port [peerHost peerPort]\n"); 67 } 68 69 70 public static void main(String args[]){ 71 int port; 72 String host,peerHost; 73 int peerPort; 74 Echo echo = null; 75 76 if(args.length > 1){ 77 try{ 78 79 host = args[0]; 80 port = Integer.parseInt(args[1]); 81 82 if(args.length ==4){ 83 peerHost = args[2]; 84 peerPort =Integer.parseInt(args[3]); 85 echo = new Echo(host,port,peerHost,peerPort); 86 }else{ 87 echo = new Echo(host,port); 88 } 89 90 Thread thread = new Thread (echo); 91 thread.start(); 92 93 BufferedReader in = new BufferedReader( 94 new InputStreamReader(System.in)); 95 String s; 96 97 s = in.readLine(); 98 Thread.currentThread().setPriority(Thread.NORM_PRIORITY); 99 while(s != null){ 100 echo.send(s+"\r\n"); 101 s = in.readLine(); 102 } 103 }catch(IOException io_ex){ 104 io_ex.printStackTrace(); 105 System.exit(1); 106 }catch(NumberFormatException num_ex){ 107 usage(); 108 num_ex.printStackTrace(); 109 System.exit(1); 110 }finally{ 111 if(echo!=null) try{echo.ss.close();}catch(Exception e){} 112 } 113 114 }else{ 115 usage(); 116 } 117 } 118 119 } | Popular Tags |