使用java写一段nio的通信代码
时间: 2024-05-05 18:16:45 浏览: 13
以下是一个简单的NIO通信代码示例,它能够建立一个服务器并接收客户端的连接请求,在客户端和服务器之间发送简单的消息。
服务器端代码:
``` 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.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NIOServer {
private static final int PORT = 8080;
public static void main(String[] args) throws IOException {
ExecutorService executor = Executors.newFixedThreadPool(10);
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
serverSocketChannel.configureBlocking(false);
System.out.println("Server started on port " + PORT);
while (true) {
SocketChannel socketChannel = serverSocketChannel.accept();
if (socketChannel != null) {
System.out.println("Client connected: " + socketChannel.getRemoteAddress());
executor.submit(new ClientHandler(socketChannel));
}
}
}
private static class ClientHandler implements Runnable {
private final SocketChannel socketChannel;
private ClientHandler(SocketChannel socketChannel) {
this.socketChannel = socketChannel;
}
@Override
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
while (socketChannel.read(buffer) > 0) {
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
System.out.println("Received message from " + socketChannel.getRemoteAddress() + ": " + new String(bytes));
buffer.clear();
}
} catch (IOException e) {
System.err.println("Error reading message from " + socketChannel.getRemoteAddress() + ": " + e.getMessage());
} finally {
try {
socketChannel.close();
} catch (IOException e) {
System.err.println("Error closing connection to " + socketChannel.getRemoteAddress() + ": " + e.getMessage());
}
}
}
}
}
```
客户端代码:
``` java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class NIOClient {
private static final String HOST = "localhost";
private static final int PORT = 8080;
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
System.out.println("Connected to server on " + socketChannel.getRemoteAddress());
String message = "Hello, server!";
ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
socketChannel.write(buffer);
System.out.println("Sent message to server: " + message);
buffer.clear();
int bytesRead = socketChannel.read(buffer);
while (bytesRead > 0) {
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
System.out.println("Received response from server: " + new String(bytes));
buffer.clear();
bytesRead = socketChannel.read(buffer);
}
socketChannel.close();
}
}
```