Java网络编程问题:TCP连接关闭异常示例
在Java的TCP编程中,如果客户端主动断开连接,可能会抛出SocketException
。具体到”TCP连接关闭异常示例”,我们可以创建一个简单的客户端程序来演示。
首先,创建一个服务器端(服务端代码省略):
ServerSocket server = new ServerSocket(8080);
Socket client = null;
try {
// Wait for a connection
client = server.accept();
System.out.println("Client connected: " + client);
// Close the connection to simulate client closing it
client.close();
} catch (IOException e) {
System.err.println("Error accepting connection: " + e);
try {
if (client != null)
client.close();
} catch (IOException f) {
System.err.println("Error closing client socket: " + f);
}
}
然后创建一个客户端,模拟主动断开连接:
import java.io.IOException;
import java.net.Socket;
public class ClientSimulator {
public static void main(String[] args) {
Socket clientSocket = null;
try {
// Connect to server (replace with server IP)
clientSocket = new Socket("localhost", 8080);
System.out.println("Connected to server: " + clientSocket);
// Simulate connection close
clientSocket.close();
System.out.println("Client socket closed.");
} catch (IOException e) {
System.err.println("Error connecting to server: " + e);
} finally {
try {
if (clientSocket != null)
clientSocket.close();
} catch (IOException f) {
System.err.println("Error closing client socket: " + f);
}
}
}
}
在这个示例中,客户端主动关闭连接,服务器端会捕获到SocketException
异常。
还没有评论,来说两句吧...