服务器端
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.PriorityQueue;
import java.util.Scanner;public class TCP_Server {private ServerSocket serverSocket=null;public TCP_Server(int port) throws IOException {serverSocket=new ServerSocket(port);}public void start() throws IOException {System.out.println("服务器启动");while (true){//通过accept方法,把内核建立好的连接拿到应用程序中//建立连接细节由内核完成Socket clientSocket=serverSocket.accept();//实现连接Thread t=new Thread(()->{try {processConnection(clientSocket);} catch (IOException e) {throw new RuntimeException(e);}});t.start();}}public void processConnection(Socket clientSocket) throws IOException {//打印日志,表示客户端连接成功System.out.printf("[%s:%d] 客户端上线\n",clientSocket.getInetAddress(),clientSocket.getPort());//数据交互try (InputStream inputStream = clientSocket.getInputStream()) {try (OutputStream outputStream = clientSocket.getOutputStream()) {//客户端可能发来多条数据,要循环处理while (true) {Scanner scanner = new Scanner(inputStream);if (!scanner.hasNext()) {//连接断开,循环结束break;}//1.读取请求解析,这里用next,因为当客户端输入空拍夫结束输入String request = scanner.next();//2.根据请求返回响应String reponse = process(request);//3.返回客户端//把字节数组写入到 OutputStreamPrintWriter printWriter = new PrintWriter(outputStream);//这里println是给客户端不是打印//println带有\n是为了客户端接收的时候以空白符结束printWriter.println(reponse);//刷新缓冲区,写道硬盘printWriter.flush();//4.打印交互内容System.out.printf("[%s:%d] req=%s,resp=%s\n", clientSocket.getInetAddress(), clientSocket.getPort(), request, reponse);}} catch (IOException e) {throw new RuntimeException(e);}finally {clientSocket.close();}}}private String process(String request) {//回显服务器return request;}public static void main(String[] args) throws IOException {TCP_Server tcpServer=new TCP_Server(800);tcpServer.start();}
}
客户端
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;public class Tcp_Client {private Socket socket=null;public Tcp_Client(String serverIp,int serverPort) throws IOException {//三次握手细节由内核自动完成socket=new Socket(serverIp,serverPort);}public void start() throws IOException {Scanner scanner=new Scanner(System.in);try( InputStream inputStream=socket.getInputStream();OutputStream outputStream=socket.getOutputStream()){PrintWriter writer=new PrintWriter(outputStream);Scanner scanner1=new Scanner(inputStream);while (true){//1.从控制台读入用户输入内容System.out.print("->");String request=scanner.next();//2.把字符串请求发给服务器,用println是为了带上\n与服务器scanner.next呼应writer.println(request);writer.flush();//3.读取服务器请求String response=scanner1.next();//4.显示返回内容System.out.println(response);}}}public static void main(String[] args) throws IOException {Tcp_Client tcpClient=new Tcp_Client("127.0.0.1",800);tcpClient.start();}
}