使用DataOutputStream,DataInputStream完成Java的Socket编程
时间: 2024-05-02 09:21:33 浏览: 121
Java Socket编程是一种网络编程,可以使用DataOutputStream和DataInputStream类来实现数据的读写和传输。以下是使用DataOutputStream和DataInputStream完成Java Socket编程的步骤:
1. 创建一个ServerSocket对象,指定端口号并监听客户端连接请求:
```
ServerSocket serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();
```
2. 使用Socket对象获取DataOutputStream和DataInputStream对象:
```
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
```
3. 使用DataOutputStream向客户端发送数据:
```
dos.writeUTF("Hello, client!");
```
4. 使用DataInputStream从客户端接收数据:
```
String message = dis.readUTF();
```
5. 关闭Socket连接和流资源:
```
dis.close();
dos.close();
socket.close();
serverSocket.close();
```
完整代码示例:
Server端:
```
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server started.");
Socket socket = serverSocket.accept();
System.out.println("Client connected.");
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
dos.writeUTF("Hello, client!");
String message = dis.readUTF();
System.out.println("Received message from client: " + message);
dis.close();
dos.close();
socket.close();
serverSocket.close();
}
}
```
Client端:
```
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8080);
System.out.println("Connected to server.");
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
String message = dis.readUTF();
System.out.println("Received message from server: " + message);
dos.writeUTF("Hello, server!");
dis.close();
dos.close();
socket.close();
}
}
```
阅读全文