网络编程:JavaSocket编程与异常处理
在Java中,Socket编程是网络通信的基础。下面我们将详细讲解Java Socket编程以及如何进行异常处理。
Socket编程基础**
- 创建Socket实例:
Socket socket = new Socket(host, port);
- 获取输出流:
OutputStream outputStream = socket.getOutputStream();
- 发送数据(如字符串):
outputStream.write(str.getBytes());
- 创建Socket实例:
异常处理**
SocketException
:一般发生在创建Socket时,如指定的主机不存在等。IOException
:通常表示在读写输入/输出流时发生了错误。例如,网络连接可能中断。
示例代码:
import java.io.*;
import java.net.*;
public class SocketExample {
public static void main(String[] args) {
try {
// 创建Socket对象
Socket socket = new Socket("localhost", 1234));
// 获取输出流
OutputStream outputStream = socket.getOutputStream();
// 发送数据,这里发送字符串
outputStream.write("Hello, Server!".getBytes());
// 关闭输出流
outputStream.close();
// 读取服务器回复的数据(如果有的话)
InputStream inputStream = socket.getInputStream();
if (inputStream.available() > 0) {
byte[] replyBytes = new byte[inputStream.available()];
inputStream.read(replyBytes);
System.out.println("Server replied: " + new String(replyBytes));
}
// 关闭输入流
inputStream.close();
} catch (SocketException e) {
System.err.println("Socket exception: " + e.getMessage());
e.printStackTrace();
} catch (IOException i) {
System.err.println("I/O exception: " + i.getMessage());
i.printStackTrace();
}
// 关闭Socket
try {
socket.close();
} catch (IOException i) {
System.err.println("Error closing socket: " + i.getMessage());
i.printStackTrace();
}
}
}
这个示例创建了一个本地的Socket连接到指定端口,并发送一条字符串消息给服务器。同时,它也处理了可能发生的SocketException和IOException异常。
还没有评论,来说两句吧...