Java网络编程中socket连接断开问题案例
在Java网络编程中,Socket的连接断开是一个常见的问题。以下是一个简单案例:
import java.io.*;
import java.net.*;
public class SocketConnectionExample {
public static void main(String[] args) {
// 创建Socket对象
try (Socket socket = new Socket("localhost", 1234)) {
System.out.println("Socket connected successfully.");
// 发送数据
try (OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream, true))) {
printWriter.println("Message sent to the server.");
printWriter.flush();
// 接收数据
try (InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)))) {
String receivedData = "";
while ((receivedData = reader.readLine())) != null) {
System.out.println("Received data: " + receivedData);
}
if (!receivedData.equals("Message sent to the server."))) {
System.err.println("Received data does not match expected.");
}
}
} catch (IOException e) {
System.err.println("Error occurred while establishing or using socket.");
e.printStackTrace();
}
} catch (UnknownHostException uhe) {
System.err.println("Failed to find the host.");
uhe.printStackTrace();
}
}
}
在这个例子中,我们尝试连接到本地主机的1234端口。如果成功,我们将发送一条消息,并接收服务器返回的消息。
如果在连接、发送或接收数据过程中遇到任何问题(如网络中断、主机未找到等),程序将捕获异常并给出相应的错误信息。
还没有评论,来说两句吧...