Java实现数据传输,客户端采用普通socket,服务端使用NIO
时间: 2024-01-07 14:02:23 浏览: 40
可以使用 Java NIO 来实现服务端的开发,同时使用普通的 Socket 来实现客户端的开发。下面是一个简单的示例:
服务端代码:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
public class NIOServer {
public static void main(String[] args) throws IOException {
// 创建 ServerSocketChannel 对象
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 绑定监听端口
serverSocketChannel.bind(new InetSocketAddress(8888));
// 设置为非阻塞模式
serverSocketChannel.configureBlocking(false);
while (true) {
// 接受客户端连接
SocketChannel socketChannel = serverSocketChannel.accept();
if (socketChannel != null) {
// 收到客户端连接
System.out.println("接收到客户端连接:" + socketChannel.getRemoteAddress());
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 读取客户端发送的数据
int bytesRead = socketChannel.read(buffer);
if (bytesRead > 0) {
// 切换缓冲区为读模式
buffer.flip();
// 解码数据
String message = StandardCharsets.UTF_8.decode(buffer).toString();
System.out.println("收到客户端消息:" + message);
// 回复客户端
buffer.clear();
buffer.put("Hello, Client!".getBytes(StandardCharsets.UTF_8));
buffer.flip();
socketChannel.write(buffer);
}
}
}
}
}
```
客户端代码:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class SocketClient {
public static void main(String[] args) throws IOException {
// 创建 Socket 对象
Socket socket = new Socket();
// 连接服务器
socket.connect(new InetSocketAddress("localhost", 8888));
// 发送消息到服务器
String message = "Hello, Server!";
socket.getOutputStream().write(message.getBytes(StandardCharsets.UTF_8));
// 接收服务器回复的消息
byte[] buffer = new byte[1024];
int bytesRead = socket.getInputStream().read(buffer);
if (bytesRead > 0) {
String reply = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
System.out.println("收到服务器消息:" + reply);
}
// 关闭连接
socket.close();
}
}
```
在上面的示例中,服务端使用 `ServerSocketChannel` 来监听客户端连接,并使用 `SocketChannel` 来读取客户端发送的数据,并回复消息。客户端使用普通的 `Socket` 来连接服务端,并发送消息到服务端,并接收服务端回复的消息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)