服务端线程池处理客户端请求,拒绝策略ThreadPoolExecutor.AbortPolicy(),客户端请求过大时Main线程抛异常:java.util.concurrent.RejectedExecutionException。实际业务可以切换其它拒绝策略。
package com.me.serverSocketDemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ServerListener {
private static final int port = 8888;
ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(2,5,5, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10), Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
public static void main(String[] args) {
ServerListener serverListener = new ServerListener();
serverListener.start();
}
public void start() {
try {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("开启监听:");
while (true) {
Socket socket = serverSocket.accept();
threadPoolExecutor.execute(new HandlerThread(socket));
}
} catch (IOException e) {
System.out.println("服务端异常!");
e.printStackTrace();
}
}
}
class HandlerThread implements Runnable {
private Socket socket ;
public HandlerThread(Socket s) {
socket = s;
try {
socket.setSoTimeout(10000);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
//读取客户端数据
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s = input.readLine();
System.out.println("服务端收到客户端发来的数据:" + s+ " 处理线程:" + Thread.currentThread().getName());
Thread.sleep(200);
input.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
System.out.println("服务端 finally 异常:" + e.getMessage());
}
}
}
}
}
client端代码:
package com.me.serverSocketDemo;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.UUID;
public class Client {
public static final int port = 8888;
public static final String host = "localhost";
public static void main(String[] args) {
System.out.println("Client run...");
while (true) {
Socket socket = null;
try {
//创建一个流套接字并将其连接到指定主机上的指定端口号
socket = new Socket(host,port);
//向服务器端发送数据
PrintStream out = new PrintStream(socket.getOutputStream());
String str ;
for (int i = 0;i < 30; i++) { //建立一次连接发三十个消息到服务端
str = Thread.currentThread().getName() + ":" + UUID.randomUUID() + ":" + System.currentTimeMillis();
System.out.println("client send :" + str);
out.println(str);
}
out.close();
} catch (Exception e) {
System.out.println("客户端异常:" + e.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
System.out.println("客户端 finally 异常:" + e.getMessage());
}
}
}
}
}
}