项目需求需要在服务端实现一个阻塞IO,即netty发送完数据之后需要阻塞线程,直到有数据返回
1条回答 默认 最新
- weixin_43547591 2018-12-20 05:10关注
@Test
public void client(){
try {
//1.获取通道
SocketChannel clientChannel = SocketChannel.open(
new InetSocketAddress("127.0.0.1", 7979));
System.out.println("client is start connecting...");
FileChannel fileChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
//2.分配指定大小的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
//3.读取本地文件,并向服务端发送文件
while(fileChannel.read(buffer)!=-1){
buffer.flip();
clientChannel.write(buffer);
buffer.clear();
}
clientChannel.shutdownOutput();//告诉服务端数据已经发送完毕,否则客户端和服务端都会处于阻塞状态
//4.接收服务端的反馈
int len = 0;
while((len = clientChannel.read(buffer))!=-1){
buffer.flip();
System.out.println(new String(buffer.array(),0,len));
buffer.clear();
}
//5.关闭通道
clientChannel.close();
fileChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}@Test
public void server(){
try {
//1.获取通道
ServerSocketChannel serverChannel = ServerSocketChannel.open();
FileChannel outChannel = FileChannel.open(
Paths.get("bio.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//2.绑定端口
serverChannel.bind(new InetSocketAddress(7979));
System.out.println("Server start in port:7979...");
//3.获取客户端连接
SocketChannel socketChannel = serverChannel.accept();
//4分配指定到小的缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//5.读取数据
while (socketChannel.read(byteBuffer)!=-1){
byteBuffer.flip();
outChannel.write(byteBuffer);
byteBuffer.clear();
}
//6.发送反馈给客户端
byteBuffer.put("服务端接收数据成功!".getBytes());
byteBuffer.flip();
socketChannel.write(byteBuffer);
//7.关闭通道
socketChannel.close();
outChannel.close();
serverChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}解决 无用评论 打赏 举报
悬赏问题
- ¥15 求daily translation(DT)偏差订正方法的代码
- ¥15 js调用html页面需要隐藏某个按钮
- ¥15 ads仿真结果在圆图上是怎么读数的
- ¥20 Cotex M3的调试和程序执行方式是什么样的?
- ¥20 java项目连接sqlserver时报ssl相关错误
- ¥15 一道python难题3
- ¥15 牛顿斯科特系数表表示
- ¥15 arduino 步进电机
- ¥20 程序进入HardFault_Handler
- ¥15 关于#python#的问题:自动化测试