try { Socket client = new Socket(socketUrl,socketPort); client.setSoTimeout(socketTimeOut); OutputStream is = client.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(client .getInputStream())); is.write(json.getBytes(StandardCharsets.UTF_8)); StringBuilder stringBuilder = new StringBuilder(); String dataResult = ""; while ((dataResult = br.readLine()) != null){ stringBuilder.append(dataResult); } log.info("【服务端返回的数据】receive={}",JsonFormatUtil.GsonFormatToString(stringBuilder.toString())); String returnData = stringBuilder.toString(); returnData = returnData.substring(24, returnData.length()); return returnData; } catch (IOException e) { log.error("sendSocket error e={}",e.getMessage()); throw new RuntimeException("网络通讯异常,请稍后再试"); }这段代码中怎么关闭Socket
时间: 2024-02-14 13:13:26 浏览: 65
关于Socket的解析以及双方即时通讯的java实现方法
在这段代码中,需要手动关闭Socket的输入流、输出流和Socket本身,以释放相关资源。修改后的代码如下:
```
try {
Socket client = new Socket(socketUrl, socketPort);
client.setSoTimeout(socketTimeOut);
OutputStream os = client.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
os.write(json.getBytes(StandardCharsets.UTF_8));
StringBuilder stringBuilder = new StringBuilder();
String dataResult = "";
while ((dataResult = br.readLine()) != null) {
stringBuilder.append(dataResult);
}
log.info("【服务端返回的数据】receive={}",JsonFormatUtil.GsonFormatToString(stringBuilder.toString()));
String returnData = stringBuilder.toString();
returnData = returnData.substring(24, returnData.length());
// 关闭输入流、输出流和Socket
br.close();
os.close();
client.close();
return returnData;
} catch (IOException e) {
log.error("sendSocket error e={}",e.getMessage());
throw new RuntimeException("网络通讯异常,请稍后再试");
}
```
在try块中使用了Socket、OutputStream和BufferedReader对象,需要在finally块中关闭这些对象。为了确保这些对象都能被关闭,在finally块中使用try-catch语句关闭它们。修改后的代码如下:
```
Socket client = null;
OutputStream os = null;
BufferedReader br = null;
try {
client = new Socket(socketUrl, socketPort);
client.setSoTimeout(socketTimeOut);
os = client.getOutputStream();
br = new BufferedReader(new InputStreamReader(client.getInputStream()));
os.write(json.getBytes(StandardCharsets.UTF_8));
StringBuilder stringBuilder = new StringBuilder();
String dataResult = "";
while ((dataResult = br.readLine()) != null) {
stringBuilder.append(dataResult);
}
log.info("【服务端返回的数据】receive={}",JsonFormatUtil.GsonFormatToString(stringBuilder.toString()));
String returnData = stringBuilder.toString();
returnData = returnData.substring(24, returnData.length());
return returnData;
} catch (IOException e) {
log.error("sendSocket error e={}",e.getMessage());
throw new RuntimeException("网络通讯异常,请稍后再试");
} finally {
try {
if (br != null) {
br.close();
}
if (os != null) {
os.close();
}
if (client != null) {
client.close();
}
} catch (IOException e) {
log.error("close socket error e={}", e.getMessage());
}
}
```
阅读全文