抓包工具用的是wireshark
1、服务端代码
package com.example.demo.tcp;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class Server {
public static void main(String[] args) {
Server s = new Server();
s.doServer();
}
public void doServer() {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(8081));
SocketChannel socketChannel = serverSocketChannel.accept();
ByteBuffer dst = ByteBuffer.allocate(1024);
FileOutputStream fileOut = new FileOutputStream("d://b.txt");
FileChannel fileChannel = fileOut.getChannel();
int len = 0;
while ((len = socketChannel.read(dst)) != -1) {
dst.flip();
fileChannel.write(dst);
dst.clear();
}
try {
Thread.sleep(1000l);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、客户端代码
package com.example.demo.tcp;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
public class Client {
public static void main(String[] args) {
Client c = new Client();
c.doClent();
}
public void doClent() {
try {
FileInputStream fileInputStream = new FileInputStream("d://a.txt");
FileChannel fileChannel = fileInputStream.getChannel();
ByteBuffer dst = ByteBuffer.allocate(1024*10);
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8081));
int len = 0;
while ((len = fileChannel.read(dst)) != -1) {
dst.flip();
socketChannel.write(dst);
dst.clear();
}
try {
Thread.sleep(1000l);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileInputStream.close();
socketChannel.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、打开wireshark,选择网卡,进入后选择筛选条件tcp.port == 8081
4、启动服务端(server)、启动客户端(client),打开wireshark,看到如下信息。
这些是tcp的握手,挥手。期中红色箭头指向的为发送的内容。
5、选择此条数据,选择Data,复制值。
6、打开jmeter,配置jmeter。删掉之前服务端生成的文件。
7、再次运行服务端,运行jmeter。可看到两个文件一致。成功。