服务端程序:
import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class EchoServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8000);//设置服务监听端口 System.out.println("等待客户端连接...");//打印提示信息 Socket clientSocket = serverSocket.accept();//等待客户端连接 Scanner scanner = new Scanner(clientSocket.getInputStream());//客户端输入流 scanner.useDelimiter(" ");//设置分隔符 PrintStream outPrintStream = new PrintStream(clientSocket.getOutputStream());//客户端输出流 boolean flag = true;//循环标记 while (flag) { if(scanner.hasNext()) {//有数据接收 String string = scanner.next().trim();//接收数据内容 if("bye".equalsIgnoreCase(string)) {//结束标记 outPrintStream.println("Bye!");//回应信息 flag = false;//结束循环 }else { outPrintStream.println("[ECHO]" + string);//Echo信息 } } } scanner.close();//关闭输入流 outPrintStream.close();//关闭输出流 clientSocket.close();//关闭客户端 serverSocket.close();//关闭服务端 } }
客户端程序:
package SocketDemo; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.util.Scanner; public class EchoClient { private static final BufferedReader KEYBOARD_INPUT = new BufferedReader(new InputStreamReader(System.in)); public static String getString(String prompt) throws Exception{//键盘信息输入 System.out.print(prompt); String string = KEYBOARD_INPUT.readLine(); return string; } public static void main(String[] args) throws Exception{ Socket clientSocket = new Socket("localhost", 8000);//定义服务端的连接信息 //现在的客户端需要有输入与输出的操作支持,所以依然要准备Scanner与PrintWriter Scanner scanner = new Scanner(clientSocket.getInputStream());//接收服务端输入内容 scanner.useDelimiter(" "); PrintStream outputPrintStream = new PrintStream(clientSocket.getOutputStream());//向服务端发送内容 boolean flag = true;//循环标记 while(flag) {//循环处理 String inputString = getString("请输入内容:").trim();//获取键盘输入数据 outputPrintStream.println(inputString);//加换行 if(scanner.hasNext()) {//服务器端有回应 System.out.println(scanner.next());//输出回应信息 } if("bye".equalsIgnoreCase(inputString)) {//结束判断 flag = false;//修改循环标记 } } scanner.close();//关闭输入流 outputPrintStream.close();//关闭输出流 clientSocket.close();//关闭客户端 } }