java实现socket连接池
时间: 2024-06-18 18:03:26 浏览: 260
java socket连接池 实现
Java实现socket连接池,可以通过自定义连接池类来实现。下面是一个简单的示例:
```
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class SocketPool {
private static final int DEFAULT_POOL_SIZE = 10;
private List<Socket> sockets;
public SocketPool(int poolSize) {
sockets = new ArrayList<>(poolSize);
for (int i = 0; i < poolSize; i++) {
try {
sockets.add(new Socket("localhost", 8080));
} catch (IOException e) {
System.err.println("Failed to create socket.");
}
}
}
public SocketPool() {
this(DEFAULT_POOL_SIZE);
}
public synchronized Socket getSocket() {
while (sockets.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
System.err.println("Interrupted while waiting for socket.");
}
}
return sockets.remove(sockets.size() - 1);
}
public synchronized void returnSocket(Socket socket) {
sockets.add(socket);
notifyAll();
}
public synchronized void closeAll() {
for (Socket socket : sockets) {
try {
socket.close();
} catch (IOException e) {
System.err.println("Failed to close socket.");
}
}
sockets.clear();
}
}
```
该连接池类通过List来维护一组Socket对象,构造函数中创建指定数量的Socket对象并加入List中。getSocket方法用于从连接池中获取一个Socket对象,如果连接池为空则等待;returnSocket方法用于将一个Socket对象归还给连接池;closeAll方法用于关闭所有连接池中的Socket对象。
阅读全文