日期:2014-05-20 浏览次数:20799 次
import java.io.*; import java.net.*; public class Client { Socket socket; BufferedReader in; PrintWriter out; boolean isQuit; public Client() { try { System.out.println("Try to Connect to 127.0.0.1:23"); socket = new Socket("10.144.205.98",23); }catch(Exception e){ System.out.println("wrong"); } isQuit = false; } public void send(){ SendThread sd = new SendThread(this); new Thread(sd).start(); } public void server(){ ServerThread st = new ServerThread(this); new Thread(st).start(); } public void over(){ try{ out.close(); in.close(); socket.close(); }catch(Exception e) { System.out.println("Wrong"); } } public Socket getSocket(){return socket;} public boolean isQuit() {return isQuit;} public void quit(boolean b){isQuit = b;} public static void main(String[] args) throws Exception{ Client c1 = new Client(); c1.server(); Thread.sleep(1000); c1.send(); } } class ServerThread implements Runnable{ Client cl; public ServerThread(Client cl){this.cl = cl;} public void run(){ BufferedReader in; Socket socket = cl.getSocket(); while(true){ if(cl.isQuit()){return;} try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); char[] buffer = new char[1024*1024*5]; String lineStr = ""; /*while((lineStr = in.readLine()) != null){ System.out.println(lineStr); }*/ int len = in.read(buffer,0,buffer.length); System.out.print(new String(buffer,0,len)); }catch(IOException e) { System.out.println("ServerThread Wrong"); e.printStackTrace(); return; } } } } class SendThread implements Runnable{ Client cl; public SendThread(Client cl){this.cl = cl;} public void run(){ PrintWriter out; Socket socket = cl.getSocket(); while(true){ try { out = new PrintWriter(socket.getOutputStream(),true); BufferedReader line = new BufferedReader(new InputStreamReader(System.in)); String tmp = line.readLine(); if(tmp.equals("quit")){ cl.quit(true); return; } out.println(tmp); }catch(IOException e) { System.out.println("SendThread Wrong"); } } } }