使用Socket API实现简单的回显服务器

一、客户端逻辑

   1.先启动客户端,和服务器建立连接【一定不要绑定端口号(由操作系统自动分配)】
   2.进入主循环
     a)读取用户输入内容
     b)构造一个请求发送给服务器
     c)读取服务器的响应数据
     d)把响应数据显示到界面上 

package com.it.bite.TcpEchoServer1;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @program: NetWork
 * @description
 * @author: wenwen
 * @create: 2021-08-06 11:10
 **/
public class TcpEchoClient {

    private Socket socket = null;
    public TcpEchoClient(String serverIp,int serverPort) throws IOException {

        //此处的实例化 Socket 过程,就是在建立TCP连接
        socket = new Socket(serverIp,serverPort);
    }
    public void start(){
        System.out.println("客户端启动");
        Scanner scan = new Scanner(System.in);
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
            while(true){
                //1.读取用户输入的内容
                System.out.println("->");
                String request = scan.nextLine();
                if("exit".equals(request)){
                    break;
                }
                //2.构造请求并发送,此处 + \n 是为了和服务器中的 readLine 相对应
                bufferedWriter.write(request + '\n');
                bufferedWriter.flush();
                //3.读取响应数据
                String response = bufferedReader.readLine();
                //4.把响应数据显示到界面上
                System.out.println(response);

            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }

}

二、服务器逻辑

1.初始化服务器
2.进入主循环
 1)先去从内核中获取到一个TCP的连接
 2)处理这个 TCP 的连接
    a)读取请求并解析
    b)根据请求计算响应
    c)把响应写回给客户端
package com.it.bite.TcpThreadPoolEchoServer3;

/**
 * @program: NetWork
 * @description
 * @author: wenwen
 * @create: 2021-08-06 16:25
 **/

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: NetWork
 * @description
 * @author: wenwen
 * @create: 2021-08-06 15:39
 **/
public class TcpThreadPoolEchoServer {
    private ServerSocket serverSocket = null;

    public TcpThreadPoolEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        //先创建一个线程池实例
        ExecutorService  executorService = Executors.newCachedThreadPool();
        while (true) {
            Socket clientSocket = serverSocket.accept();
          executorService.execute(new Runnable() {
              @Override
              public void run() {
                  try {
                      processConnetcion(clientSocket);
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          });
        }
    }

    public void processConnetcion(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线!\n", clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        String request = null;
        String response = null;
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))) {

            while (true) {

                //1.读取请求并解析(此处的 readLine 对应客户端发送数据的格式,必须是按行发送)
                request = bufferedReader.readLine();
                //2.根据请求计算响应
                response = process(request);
                //3.把响应写回到客户端(客户端按行来读)
                bufferedWriter.write(response + "\n");
                bufferedWriter.flush();
                System.out.printf("[%s %d] req: %s;resp: %s \n", clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(), request, response);

            }

        }catch(IOException e){
            System.out.printf("[%s %d] 客户端下线 !\n", clientSocket.getInetAddress().toString(),
                    clientSocket.getPort());

        }

    }

    private String process(String request) {
        return request;
    }
    public static void main (String[] args) throws IOException {
        TcpThreadPoolEchoServer server = new TcpThreadPoolEchoServer(9090);
        server.start();

    }
}


三、运行截图 

使用Socket API实现简单的回显服务器_第1张图片

使用Socket API实现简单的回显服务器_第2张图片 

 

你可能感兴趣的:(操作系统)