java
package TCP6;
// 完成TCP通信服务端 多发多收
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的对象 同时为服务端注册端口
ServerSocket serverSocket = new ServerSocket(8888);
// 创建线程池 负责处理通信管道的任务
ThreadPoolExecutor pool= new ThreadPoolExecutor(4*2,4*2, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(8), Executors.defaultThreadFactory());
while (true) {
//2:使用serverSocket 对象 调用accept 方法 等待客户端连接请求
Socket socket= serverSocket.accept();
// 3:把客户端对应的Socket 通信管道 交给独立的线程负责
pool.execute(new ServerReaderRunnable(socket));
}
}
}
java
package TCP6;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Random;
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;font-size:120px;text-align:center'>你好你还好吗 6666</div> ");
socket.close();
ps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}