测试测试开发写给测试的测试软件该用什么测试软件去测试?
读完这个问题时你已经对 测 这个字感到陌生了
@Test
void client() throws IOException {
Path path = Paths.get("banner.txt");
ByteBuffer buffer = ByteBuffer.allocate((int)path.toFile().length());
FileChannel fc = FileChannel.open(path, StandardOpenOption.READ,
StandardOpenOption.WRITE);
/*使用SocketChannel连通服务端*/
SocketChannel sc = SocketChannel.open(new InetSocketAddress("127.0.0.1",898));
fc.read(buffer);
buffer.flip();
String s = new String(buffer.array(),0,buffer.limit());
System.out.println(s);
/*通道有内容写入时会交给服务端处理,此时客户端处于阻塞状态*/
sc.write(buffer);
/*等待服务端处理完毕后需关闭通道的写入,
* 否则会一直保持连通*/
sc.shutdownOutput();
ByteBuffer buffer1 = ByteBuffer.allocate(12);
sc.read(buffer1);
buffer1.flip();
String msg = new String(buffer1.array(),0,buffer1.limit());
System.out.println(msg);
sc.close();
fc.close();
}
@Test
void server() throws IOException {
/*服务端通道*/
ServerSocketChannel ssc = ServerSocketChannel.open();
/*设置端口号*/
ssc.bind(new InetSocketAddress(898));
/*接收客户端通道,如果没有客户端消息可以接收则一直处于阻塞状态*/
SocketChannel sc = ssc.accept();
ByteBuffer buffer = ByteBuffer.allocate(1024*1024);
FileChannel fc = FileChannel.open(Paths.get("bannerCopy.txt"),
StandardOpenOption.WRITE,
StandardOpenOption.READ,
StandardOpenOption.CREATE);
while (sc.read(buffer)!=-1){
buffer.flip();
fc.write(buffer);
buffer.clear();
}
/*处理请求完毕后向客户端回复一个提示信息*/
ByteBuffer buffer1 = ByteBuffer.allocate(12);
/*注意,UTF-8字符集下每个中文字符占用三个字节*/
buffer1.put("发送成功".getBytes());
buffer1.flip();
sc.write(buffer1);
fc.close();
ssc.close();
sc.close();
}
/*非阻塞式NIO*/
@Test
void client1() throws IOException {
SocketChannel sc = SocketChannel
.open(new InetSocketAddress("127.0.0.1",880));
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("fsdfsdfs".getBytes());
buffer.flip();
sc.write(buffer);
sc.shutdownOutput();
ByteBuffer buffer1 = ByteBuffer.allocate(1024*1024);
sc.read(buffer1);
buffer1.flip();
System.out.println(new String(buffer1.array(),0, buffer1.limit()));
sc.close();
}
/*使用多个客户端同时发送消息*/
@Test
void client2() throws IOException {
new SocketChannelTest().client1();
}
@Test
void server1() throws IOException {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.bind(new InetSocketAddress(880));
/*利用线程池异步处理客户端提交的请求*/
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10,20,2,
TimeUnit.SECONDS,
new LinkedBlockingQueue(),
new ThreadPoolExecutor.DiscardPolicy()
);
ByteBuffer buffer = ByteBuffer.allocate(1024*1024*5);
while (true){
SocketChannel sc = ssc.accept();
/*每有一个请求过来就直接提交给线程池去处理*/
threadPool.submit(() -> {
StringBuilder sb = new StringBuilder();
while (true){
try {
if (!(sc.read(buffer)==-1)) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
buffer.flip();
sb.append(new String(buffer.array(),0,buffer.limit()));
buffer.clear();
}
ByteBuffer msg = ByteBuffer.allocate(12).put("发送成功".getBytes());
msg.flip();
try {
sc.write(msg);
System.out.println(sb);
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}