java客户端服务端通信
时间: 2023-12-04 16:41:02 浏览: 97
java实现客户端与服务端通信
5星 · 资源好评率100%
以下是Java编写的局域网实时通信客户端和服务端的通信方法:
客户端:
1. 导入Socket和IO相关的包
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
```
2. 创建Socket对象,指定服务器地址和端口号
```java
Socket socket = new Socket("localhost",9999);
```
3. 获取输入输出流,进行数据传输
```java
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
```
4. 发送数据
```java
out.println("Hello Server");
```
5. 接收数据
```java
String response = in.readLine();
System.out.println("Server response: " + response);
```
6. 关闭连接
```java
in.close();
out.close();
socket.close();
```
服务端:
1. 导入Socket和IO相关的包
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
```
2. 创建ServerSocket对象,指定端口号
```java
ServerSocket serverSocket = new ServerSocket(9999);
```
3. 监听客户端连接,获取Socket对象
```java
Socket socket = serverSocket.accept();
```
4. 获取输入输出流,进行数据传输
```java
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
```
5. 接收数据
```java
String request = in.readLine();
System.out.println("Client request: " + request);
```
6. 发送数据
```java
out.println("Hello Client");
```
7. 关闭连接
```java
in.close();
out.close();
socket.close();
serverSocket.close();
```
阅读全文