企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
简单服务器与客户端传输信息 Test.java ~~~ package chat.a1; import java.net.*; import java.io.*; public class Test { //构造函数 public Test(){ try { //new一个端口 ServerSocket ss=new ServerSocket(9999); System.out.println("服务器正在监听.."); Socket s=ss.accept(); //System.out.println("我不会显示");//当没有客户端的消息传输过来时,这句话是不会输出的 InputStreamReader isr=new InputStreamReader(s.getInputStream()); BufferedReader br = new BufferedReader(isr); String xinxi = br.readLine(); System.out.println(xinxi); PrintWriter pw =new PrintWriter(s.getOutputStream(),true); pw.println("我是服务器"); } catch (Exception e) { // TODO: handle exception } } public static void main(String[] args) { Test t=new Test(); } } ~~~ Test1.java ~~~ package chat.a1; import java.net.*; import java.io.*; public class Test1 { public static void main(String[] args) { Test1 t=new Test1(); } public Test1(){ try { Socket s=new Socket("127.0.0.1",9999); PrintWriter pw =new PrintWriter(s.getOutputStream(),true); pw.println("我是客户端"); InputStreamReader isr=new InputStreamReader(s.getInputStream()); BufferedReader br = new BufferedReader(isr); String fanhui = br.readLine(); System.out.println(fanhui); } catch (Exception e) { // TODO: handle exception } } } ~~~ 先启动服务器Test.java,再启动客户端Test1.java 服务器控制台: ![](https://box.kancloud.cn/4799e0021749a544b6822a93b14ae7c0_1065x179.png) 客户端控制台: ![](https://box.kancloud.cn/c84bb6247e041a0e2d5538c4282e0a89_1233x249.png)