文件传输后关闭 ServerSocket 时出错 Java
Error closing ServerSocket after file transfer Java
我有下面的代码 当我没有关闭 ServerSocket 语句时,我收到一条错误消息,说这是资源泄漏,但是当我添加关闭语句时,Eclipse 告诉我代码无法访问,我该如何更改代码在 while 语句之外关闭套接字?
serverSocket = new ServerSocket(ServerPort);
File incomingFile = new File("testfile.txt");
while (true) {
System.out.println("Waiting For File");
Socket incomingSocket = serverSocket.accept();
byte[] mybytearray = new byte[(int) incomingFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(incomingFile));
bis.read(mybytearray, 0, mybytearray.length);
bis.close();
OutputStream os = incomingSocket.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
if (incomingSocket != null) {
incomingSocket.close();
}
}
if(serverSocket != null) {
serverSocket.close();
}
防止资源泄漏的正确方法是使用try..finally
serverSocket = new ServerSocket(serverPort);
try {
File incomingFile = new File("testfile.txt");
while (true) {
// your code
}
} finally {
serverSocket.close();
}
或像这样使用 try-with-resources
结构
try (serverSocket = new ServerSocket(serverPort)) {
File incomingFile = new File("testfile.txt");
while (true) {
// your code
}
}
无法访问代码的原因是您的 while
循环未终止。另请注意,serverSocket
在代码中的那个位置不能为 null,因为除非抛出异常,否则构造函数必须始终生成一个新实例。
我有下面的代码 当我没有关闭 ServerSocket 语句时,我收到一条错误消息,说这是资源泄漏,但是当我添加关闭语句时,Eclipse 告诉我代码无法访问,我该如何更改代码在 while 语句之外关闭套接字?
serverSocket = new ServerSocket(ServerPort);
File incomingFile = new File("testfile.txt");
while (true) {
System.out.println("Waiting For File");
Socket incomingSocket = serverSocket.accept();
byte[] mybytearray = new byte[(int) incomingFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(incomingFile));
bis.read(mybytearray, 0, mybytearray.length);
bis.close();
OutputStream os = incomingSocket.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
if (incomingSocket != null) {
incomingSocket.close();
}
}
if(serverSocket != null) {
serverSocket.close();
}
防止资源泄漏的正确方法是使用try..finally
serverSocket = new ServerSocket(serverPort);
try {
File incomingFile = new File("testfile.txt");
while (true) {
// your code
}
} finally {
serverSocket.close();
}
或像这样使用 try-with-resources
结构
try (serverSocket = new ServerSocket(serverPort)) {
File incomingFile = new File("testfile.txt");
while (true) {
// your code
}
}
无法访问代码的原因是您的 while
循环未终止。另请注意,serverSocket
在代码中的那个位置不能为 null,因为除非抛出异常,否则构造函数必须始终生成一个新实例。