合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
服务器与客户端互发信息 Test2.java ~~~ package chat.a2; import java.net.*; import java.io.*; public class Test2 { //构造函数 public Test2(){ try { //new一个端口 ServerSocket ss=new ServerSocket(9999); System.out.println("服务器正在监听.."); Socket s=ss.accept();//接收服务器传过来的信息 InputStreamReader isr=new InputStreamReader(s.getInputStream()); BufferedReader br = new BufferedReader(isr); PrintWriter pw =new PrintWriter(s.getOutputStream(),true); InputStreamReader isr2=new InputStreamReader(System.in);//输入信息 BufferedReader br2 = new BufferedReader(isr2); while(true){ String xinxi = br.readLine(); System.out.println("客户端说:"+xinxi); System.out.println("我说"); String fasong = br2.readLine(); pw.println(fasong); } } catch (Exception e) { // TODO: handle exception } } public static void main(String[] args) { Test2 t=new Test2(); } } ~~~ Test3.java ~~~ package chat.a2; import java.net.*; import java.io.*; public class Test3 { public static void main(String[] args) { Test3 t=new Test3(); } public Test3(){ try { Socket s=new Socket("127.0.0.1",9999); PrintWriter pw =new PrintWriter(s.getOutputStream(),true); InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); InputStreamReader isr2=new InputStreamReader(s.getInputStream()); BufferedReader br2 = new BufferedReader(isr2); while(true){ System.out.println("我发言:"); String fasong = br.readLine(); pw.println(fasong); String jieshou = br2.readLine(); System.out.println("服务器说:"+jieshou); } } catch (Exception e) { // TODO: handle exception } } } ~~~ 先启动服务器Test2.java,再启动客户端Test3.java 服务器控制台: ![](https://box.kancloud.cn/058c8897981e6baa6f3470f885a8592e_1237x275.png) 客户端控制台: ![](https://box.kancloud.cn/5d73635b8098ccb48993b9e7c6894c9b_1214x266.png)