关于Java网络编程:socket连接异常案例
在Java的网络编程中,Socket连接可能会出现各种异常。以下是一个具体的Socket连接异常案例:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class SocketExceptionExample {
public static void main(String[] args) {
// 创建一个Socket对象
try (Socket socket = new Socket("localhost", 1234)) {
// 连接成功,打印消息
System.out.println("Socket connected successfully!");
// 发送数据
byte[] message = "Hello, Server!".getBytes();
socket.getOutputStream().write(message);
// 接收数据
byte[] receivedData = new byte[1024];
int lengthReceived = socket.getInputStream().read(receivedData));
String dataReceived = new String(receivedData, 0, lengthReceived));
// 打印接收的数据
System.out.println("Received Data: " + dataReceived);
} catch (IOException e) {
// 处理连接异常
System.err.println("Socket connection failed with error: " + e.getMessage());
e.printStackTrace();
}
}
}
在这个例子中,如果目标主机”localhost”不存在或者端口号1234不可达,那么Socket
的连接就会抛出IOException
。
还没有评论,来说两句吧...