Server:
package com.net.tcp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(30000); while(true){ Socket s= ss.accept(); try(BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()))){ String line; while(true){ line=in.readLine(); if(line.equals("end")){ System.out.println("over"); break; }else{ System.out.println(line); } } PrintStream ps = new PrintStream(s.getOutputStream()); ps.println("收到消息\n"); ps.println("end"); ps.flush(); in.close(); ps.close(); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Client:
package com.net.tcp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; public class MyClient { public static void main(String[] args) { Socket s = new Socket(); try { s.connect(new InetSocketAddress("127.0.0.1", 30000), 10000); PrintStream ps = new PrintStream(s.getOutputStream()); ps.println("发送消息\n"); ps.println("发送消息3\n"); ps.println("end");//用作结束标记 ps.flush(); try(BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()))){ String line; while(true){ line=in.readLine(); if(line.equals("end")){ System.out.println("over"); break; }else{ System.out.println(line); } } try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } in.close(); ps.close(); } s.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
来源:https://www.cnblogs.com/moonpool/p/5518797.html