java
package com.zz.tcp.BC;
import com.zz.tcp.case1.ServerReaderThread;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Server {
public static void main(String args[]) throws Exception{
System.out.println("========服务端启动========");
//1.创建ServerSocket的对象,调用一个accept方法,等待客户端的连接请求
ServerSocket serverSocket = new ServerSocket(8888);
//创建出一个线程池,负责处理线程融信管道的任务
ThreadPoolExecutor pool = new ThreadPoolExecutor(8 * 2, 8 * 2, 0,
TimeUnit.DAYS, new ArrayBlockingQueue <>(8), Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
while (true){
//2.使用ServerSocket对象,调用一个accept方法,等待客户端的连接请求
Socket socket = serverSocket.accept();
System.out.println("有人上线了" + socket.getRemoteSocketAddress());
//3.把这个客户端对应的socket通信管道,交给一个独立的线程复制处理
pool.execute(new ServerReaderRunnable(socket));
}
}
}
java
package com.zz.tcp.BC;
import java.io.*;
import java.net.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:blue;font-size:120px;text-align:center'>你好,世界!</div>");
ps.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}