java nio tcp服务端接收 文字或者文件,接收到文字时打印,接收到文件时保存到D盘
时间: 2023-06-11 20:06:52 浏览: 163
以下是一个简单的Java NIO TCP服务端代码,可以接收文本和文件:
```java
import java.io.*;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Iterator;
import java.util.Set;
public class NioTcpServer {
private static final int PORT = 8888;
private static final int BUFFER_SIZE = 1024;
private static final Charset CHARSET = StandardCharsets.UTF_8;
private static final String FILE_SAVE_DIR = "D:\\";
public static void main(String[] args) throws IOException {
// 创建 Selector 和 Channel
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(PORT));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server started on port " + PORT);
while (true) {
int readyChannels = selector.select();
if (readyChannels == 0) {
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isAcceptable()) {
// 接收客户端连接请求
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("Accepted connection from " + socketChannel.getRemoteAddress());
} else if (key.isReadable()) {
// 读取客户端发送的数据
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = socketChannel.read(buffer)) > 0) {
buffer.flip();
byte[] bytes = new byte[bytesRead];
buffer.get(bytes);
byteArrayOutputStream.write(bytes);
buffer.clear();
}
byte[] data = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
// 判断是文本还是文件
if (isTextData(data)) {
String text = new String(data, CHARSET);
System.out.println("Received text: " + text);
} else {
String filename = getFilename();
Path filePath = Paths.get(FILE_SAVE_DIR, filename);
Files.write(filePath, data, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
System.out.println("Received file: " + filename);
}
}
keyIterator.remove();
}
}
}
/**
* 判断数据是否为文本
*/
private static boolean isTextData(byte[] data) {
return !isBinaryData(data);
}
/**
* 判断数据是否为二进制
*/
private static boolean isBinaryData(byte[] data) {
for (byte b : data) {
if (b < 0x09) return true;
if (b > 0x0d && b < 0x20) return true;
}
return false;
}
/**
* 生成文件名
*/
private static String getFilename() {
return "file_" + System.currentTimeMillis();
}
}
```
这个服务端会一直监听端口,当有连接请求时接收客户端连接。当客户端发送数据时,服务端会读取数据并判断是文本还是文件,如果是文本则打印,如果是文件则保存到指定目录下。
阅读全文