java实现tcp和udp网络通信
时间: 2023-11-21 08:57:23 浏览: 102
Java可以通过TCP和UDP协议实现网络通信。其中,TCP协议提供面向连接的、可靠的数据传输服务,而UDP协议则提供无连接的、不可靠的数据传输服务。
下面是Java实现TCP网络通信的例子:
```java
// 服务器端
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String message = null;
while ((message = br.readLine()) != null) {
System.out.println("接收到客户端消息:" + message);
}
br.close();
socket.close();
serverSocket.close();
// 客户端
Socket socket = new Socket("127.0.0.1", 8888);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.write("Hello, server!");
pw.flush();
socket.shutdownOutput();
socket.close();
```
下面是Java实现UDP网络通信的例子:
```java
// 服务器端
DatagramSocket serverSocket = new DatagramSocket(8888);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("接收到客户端消息:" + message);
serverSocket.close();
// 客户端
DatagramSocket clientSocket = new DatagramSocket();
String message = "Hello, server!";
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("127.0.0.1"), 8888);
clientSocket.send(packet);
clientSocket.close();
```
阅读全文