代码演示如下:
服务端
public class Server { public static void main(String[] args) throws Exception{ System.out.println("服务端开启!"); //1.创建ServerSocket的对象,同时为服务端注册端口。 ServerSocket serverSocket = new ServerSocket(8080); while (true) { //2.使用serverSocket对象,调用一个accept方法,等待客户端的连接请求 Socket socket = serverSocket.accept(); System.out.println("有人上线了:" + socket.getRemoteSocketAddress()); //3.把这个客户端对应的socket通信管道,交给一个对立的线程负责处理 new ServerReaderThread(socket).start(); } } }
服务线程类:
public class ServerReaderThread extends Thread { private Socket socket; public ServerReaderThread(Socket socket) { this.socket = socket; } @Override public void run() { try { OutputStream os = socket.getOutputStream(); PrintStream ps = new PrintStream(os); ps.println("HTTP/1.1 200 OK"); ps.println("Content-Type:text/html;charset=UTF-8"); ps.println(); // 换行 ps.println("<div style='color:red;front-size:120px;text-align:center'>黑马程序员666<div>"); ps.close(); socket.close(); } catch (Exception e) { } } }
扩展知识:
每次请求都开一个新线程好吗?
答:不好,高并发时,容易宕机!
优化代码如下:
服务端
public class Server { public static void main(String[] args) throws Exception{ System.out.println("服务端开启!"); //1.创建ServerSocket的对象,同时为服务端注册端口。 ServerSocket serverSocket = new ServerSocket(8080); //创建出一个线程池,负责处理通信管道的任务 ThreadPoolExecutor pool = new ThreadPoolExecutor(16 * 2, 16 * 2,0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(8), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); while (true) { //2.使用serverSocket对象,调用一个accept方法,等待客户端的连接请求 Socket socket = serverSocket.accept(); //3.把这个客户端对应的socket通信管道,交给一个对立的线程负责处理 pool.execute(new ServerReaderRunnable(socket)); } } }
服务类线程池
public class ServerReaderRunnable implements Runnable { private Socket socket; public ServerReaderRunnable(Socket socket) { this.socket = socket; } @Override public void run() { try { OutputStream os = socket.getOutputStream(); PrintStream ps = new PrintStream(os); ps.println("HTTP/1.1 200 OK"); ps.println("Content-Type:text/html;charset=UTF-8"); ps.println(); // 换行 ps.println("<div style='color:red;front-size:120px;text-align:center'>黑马程序员666<div>"); ps.close(); socket.close(); } catch (Exception e) { } } }