tcp nio服务端和客户端例子
时间: 2023-08-13 20:39:11 浏览: 122
以下是一个使用Java NIO实现的TCP Server和Client的示例代码:
TCP Server:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class TCPServer {
private Selector selector;
private ByteBuffer buffer = ByteBuffer.allocate(1024);
public TCPServer(int port) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(port));
selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server started on port " + port);
}
private void start() throws IOException {
while (true) {
selector.select();
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = keys.next();
keys.remove();
if (!key.isValid()) {
continue;
}
if (key.isAcceptable()) {
accept(key);
} else if (key.isReadable()) {
read(key);
} else if (key.isWritable()) {
write(key);
}
}
}
}
private void accept(SelectionKey key) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("Accepted connection from " + socketChannel.getRemoteAddress());
}
private void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
buffer.clear();
int bytesRead = socketChannel.read(buffer);
if (bytesRead == -1) {
socketChannel.close();
System.out.println("Connection closed by " + socketChannel.getRemoteAddress());
return;
}
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println("Received data from " + socketChannel.getRemoteAddress() + ": " + new String(data));
socketChannel.register(selector, SelectionKey.OP_WRITE, data);
}
private void write(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
byte[] data = (byte[]) key.attachment();
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
socketChannel.write(byteBuffer);
System.out.println("Sent data to " + socketChannel.getRemoteAddress() + ": " + new String(data));
socketChannel.register(selector, SelectionKey.OP_READ);
}
public static void main(String[] args) throws IOException {
TCPServer server = new TCPServer(8080);
server.start();
}
}
```
TCP Client:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class TCPClient {
private SocketChannel socketChannel;
private ByteBuffer buffer = ByteBuffer.allocate(1024);
public TCPClient(String host, int port) throws IOException {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress(host, port));
}
private void start() throws IOException {
while (!socketChannel.finishConnect()) {
// Wait for connection to be established
}
System.out.println("Connected to server " + socketChannel.getRemoteAddress());
String message = "Hello, server!";
buffer.put(message.getBytes());
buffer.flip();
socketChannel.write(buffer);
System.out.println("Sent data to server: " + message);
buffer.clear();
int bytesRead = socketChannel.read(buffer);
if (bytesRead == -1) {
socketChannel.close();
System.out.println("Connection closed by server");
return;
}
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println("Received data from server: " + new String(data));
socketChannel.close();
}
public static void main(String[] args) throws IOException {
TCPClient client = new TCPClient("localhost", 8080);
client.start();
}
}
```
阅读全文