import java.io.*; import java.net.*; import java.util.Scanner; public class client { public static void main(String[] args) { work.link(); new MyworkWriter().start(); } } class work { //是否在线 static boolean online=false; static Socket s1 =null; static BufferedReader in=null; static PrintWriter out=null; static void set_online() { online=true; } static void set_offline() { online=false; } static void link() { try{ //链接sever端 s1 = new Socket("127.0.0.1",9998); //实例化输入流 in= new BufferedReader(new InputStreamReader(s1.getInputStream())); out=new PrintWriter(s1.getOutputStream(),true); set_online(); System.out.println("已连接"); new MyworkReader ().start(); }catch(SocketException e){ System.out.println("无法与对方主机建立连接"); set_offline(); System.out.println(e); }catch(IOException e){ System.out.println("输入输出出错"); set_offline(); System.out.println(e); } } } //创建一个进程用来写入并发送数据 class MyworkWriter extends Thread { public void run() { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String msg; try { while(true) { msg = br.readLine(); msg = msg.trim(); switch(msg) { case "exit": System.out.println("exit,程序退出"); System.exit(0); break; case "link": System.out.println("link,连接远程主机"); if(work.online) { System.out.println("在线状态,不能重复连接"); } else { work.link(); } break; case "help": System.out.println("help,帮助"); System.out.println("exit,退出程序"); System.out.println("link,连接主机"); System.out.println("close,关闭连接"); break; case "close": System.out.println("close,关闭连接"); work.s1.close(); break; default: if(work.online) { work.out.println(msg); } else { System.out.println("你已经离线状态,为您重新连接服务器."); work.link(); if(work.online) { work.out.println(msg); } else { System.out.println("还是不能连接,可能远程服务器已经关闭."); } } } } } catch(IOException e) { System.out.println("发送数据时出错"); System.out.println(e); } } } //创建一个进程用来进行接收读取数据 class MyworkReader extends Thread { public void run() { String msg; try { while(true) { msg = work.in.readLine(); System.out.println("对方说:"+msg); if(msg.equals("bye")) { System.out.println("对方下线,程序退出"); work.set_offline(); break; } } }catch(IOException e) { System.out.println("读数据时出错,可能对方主机掉线"); System.out.println(e); work.set_offline(); } } }