1. 传统 IO 方式
1.1 传统 IO 服务器端
public class OidIOServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(7001);
while (true) {
Socket socket = serverSocket.accept();
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
try {
byte[] byteArray = new byte[4096];
while (true) {
int read = inputStream.read(byteArray, 0, byteArray.length);
if (read == -1) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
1.2 传统 IO 客户端
public class OidIOClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 7001);
String fileName = "book.zip";
InputStream inputStream = new FileInputStream(fileName);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
byte[] buffer = new byte[4096];
long readCount;
long total = 0;
long startTime = System.currentTimeMillis();
while ((readCount = inputStream.read(buffer)) >= 0) {
total += readCount;
outputStream.write(buffer);
}
System.out.println("发送字节数: " + total + ", 耗时: " + (System.currentTimeMillis()-startTime));
outputStream.close();
socket.close();
inputStream.close();
}
}
2. NIO 方式
2.1 NIO 服务器端
public class NewIOServer {
public static void main(String[] args) throws Exception {
InetSocketAddress socketAddress = new InetSocketAddress(7001);
ServerSocketChannel socketChannel = ServerSocketChannel.open();
ServerSocket serverSocket = socketChannel.socket();
serverSocket.bind(socketAddress);
ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
while (true) {
SocketChannel channel = socketChannel.accept();
int readCount = 0;
while (-1 != readCount) {
try {
readCount = channel.read(byteBuffer);
} catch (Exception e) {
}
byteBuffer.rewind();
}
}
}
}
2.2 NIO 客户端
public class NewIOClient {
public static void main(String[] args) throws Exception {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 7001));
String fileName = "book.zip";
FileChannel channel = new FileInputStream(fileName).getChannel();
long start = System.currentTimeMillis();
long transferCount = 0;
long ls = 8 * 1024 * 1024;
long size = channel.size();
long count = size / ls;
long flag = size % ls;
if (flag != 0) {
count++;
}
long startPosition = 0;
for (int i = 0; i < count; i++) {
long transfer = channel.transferTo(startPosition, ls, socketChannel);
transferCount += transfer;
startPosition += ls;
}
System.out.println("发送的总的字节数 = " + transferCount + ", 耗时 = " + (System.currentTimeMillis()-start));
}
}