//这是客户端
package com.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class Client { public Client() { 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 info = br.readLine(); pw.println(info); String res = br2.readLine(); System.out.println("服务器说"+ res); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Client client = new Client(); } }
//这是服务器
package com.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { Server server =new Server(); } public Server(){ try { System.out.println("服务器在9999监听"); ServerSocket ss = new ServerSocket(9999); 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 infoFromClient = br.readLine(); System.out.println("客户端发来"+infoFromClient); System.out.println("请输入你想对客户端说的话"); String response = br2.readLine(); pw.println(response); } } catch (IOException e) { e.printStackTrace(); } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步