最近使用递归进行socket重连,导致栈溢出,特此记录一下
public class SocketUtil {
private Socket socket;
private OutputStream outputStream;
private InputStream inputStream;
private boolean isReconnected = true;
private final ExecutorService mThreadPool;
private final String ip = "192.168.1.31";
private final int port = 8899;
SocketUtil() {
mThreadPool = Executors.newFixedThreadPool(1);
}
public void releaseSocket() {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
outputStream = null;
inputStream = null;
socket = null;
}
public void sendMsg(final String msg) {
mThreadPool.execute(() -> {
if (socket == null) {
while (socket == null && isReconnected) {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), 2000);
outputStream = socket.getOutputStream();
outputStream.write(msg.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
} catch (IOException e) {
handleConnectionException(e);
}
}
} else {
try {
outputStream = socket.getOutputStream();
outputStream.write(msg.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
} catch (IOException e) {
handleConnectionException(e);
}
}
});
}
private void receiveMsg() {
mThreadPool.execute(() -> {
while (isReconnected) {
if (socket == null) {
while (socket == null && isReconnected) {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), 2000);
inputStream = socket.getInputStream();
int available = inputStream.available();
if (inputStream != null && available > 0) {
byte[] buffer = new byte[4096];
int len = inputStream.read(buffer);
String message = new String(buffer, 0, len, StandardCharsets.UTF_8);
System.out.println(message);
}
} catch (IOException e) {
handleConnectionException(e);
}
}
} else {
try {
inputStream = socket.getInputStream();
int available = inputStream.available();
if (inputStream != null && available > 0) {
byte[] buffer = new byte[4096];
int len = inputStream.read(buffer);
String message = new String(buffer, 0, len, StandardCharsets.UTF_8);
System.out.println(message);
}
} catch (IOException e) {
handleConnectionException(e);
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
private void handleConnectionException(IOException e) {
if (e instanceof SocketTimeoutException) {
System.out.println("连接超时");
releaseSocket();
} else if (e instanceof NoRouteToHostException) {
System.out.println("地址不存在");
releaseSocket();
} else if (e instanceof ConnectException) {
System.out.println("连接异常或被拒绝");
releaseSocket();
} else {
System.out.println("连接断开");
releaseSocket();
}
}
public static void main(String[] args) {
SocketUtil util = new SocketUtil();
util.sendMsg("1111");
util.receiveMsg();
}
}
本文描述了在使用递归方式实现Socket重连时遇到的栈溢出问题,作者分享了如何在SocketUtil类中处理连接异常并重新建立连接的过程。
1971

被折叠的 条评论
为什么被折叠?



