4.1

所花时间(包括上课):1.5

打码量(行):240

博客量(篇):1

了解到知识点:学习Server端代码编写

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

 

public class SimpleServer {

 

    public static void main(String[] args) {

        int portNumber = 12345;

 

        try {

            // 创建 ServerSocket,监听指定端口

            ServerSocket serverSocket = new ServerSocket(portNumber);

            System.out.println("Server started. Listening on port " + portNumber);

 

            // 等待客户端连接

            while (true) {

                Socket clientSocket = serverSocket.accept();

                System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());

 

                // 处理客户端数据

                handleClient(clientSocket);

            }

 

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

 

    private static void handleClient(Socket clientSocket) {

        try {

            // 获取客户端输入流

            BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

 

            // 获取客户端输出流

            PrintWriter output = new PrintWriter(clientSocket.getOutputStream(), true);

 

            String inputLine;

 

            // 读取客户端发送的数据,并发送响应

            while ((inputLine = input.readLine()) != null) {

                System.out.println("Received from client: " + inputLine);

 

                // 将消息返回给客户端

                output.println("Server received: " + inputLine);

 

                if ("exit".equalsIgnoreCase(inputLine)) {

                    break;

                }

            }

 

            // 关闭连接

            input.close();

            output.close();

            clientSocket.close();

 

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

posted @ 2024-04-01 13:12  赵千万  阅读(8)  评论(0编辑  收藏  举报