在Java Socket中處理大數據流時,需要考慮到內存和性能的問題
BufferedInputStream
和BufferedOutputStream
來實現緩沖。import java.io.*;
import java.net.*;
public class BigDataSocketServer {
public static void main(String[] args) throws IOException {
int port = 12345;
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket socket = serverSocket.accept();
InputStream inputStream = new BufferedInputStream(socket.getInputStream());
OutputStream outputStream = new BufferedOutputStream(socket.getOutputStream());
// 處理數據流
handleDataStream(inputStream, outputStream);
inputStream.close();
outputStream.close();
socket.close();
}
}
private static void handleDataStream(InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
// 處理數據
outputStream.write(buffer, 0, bytesRead);
}
}
}
private static void handleDataStream(InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
int totalBytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
totalBytesRead += bytesRead;
// 處理數據
outputStream.write(buffer, 0, bytesRead);
if (totalBytesRead >= CHUNK_SIZE) {
// 發送或接收下一個數據塊
totalBytesRead = 0;
}
}
}
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class BigDataSocketServer {
public static void main(String[] args) throws IOException {
int port = 12345;
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = socketChannel.read(buffer);
if (bytesRead == -1) {
socketChannel.close();
} else {
buffer.flip();
// 處理數據
buffer.clear();
}
}
}
}
}
}
通過以上方法,可以有效地在Java Socket中處理大數據流,同時避免內存和性能問題。