public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
ServerSocket ss = serverSocketChannel.socket();
ss.setReuseAddress(true);//地址重用
ss.bind(new InetSocketAddress("localhost",9026));
System.out.println("监控端口:"+new InetSocketAddress("localhost",9026).toString());
//分配一个新的字节缓冲区
ByteBuffer allocate = ByteBuffer.allocate(4096);
//读取数据
while (true){
SocketChannel channel = serverSocketChannel.accept();//接收数据
System.out.println("accepted:"+channel);
channel.configureBlocking(true);//设置阻塞,接不到就停
int nread=0;
while(nread !=-1){
try {
System.out.println("往缓冲区里读");
nread = channel.read(allocate); //往缓冲区里读
byte[] array=allocate.array();//数据转换array
//打印
String string = new String(array,0,allocate.position());
System.out.println(string);
allocate.clear();
}catch (Exception e){
e.printStackTrace();
nread = -1;
}
}
}
}public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
//打开socket的nio管道
SocketChannel sc = SocketChannel.open();
sc.connect(new InetSocketAddress("localhost",9026));//绑定
sc.configureBlocking(true);//设置阻塞
//将文件放到channel中
FileChannel channel = new FileInputStream("/Users/limeng/Public/aa.txt").getChannel();
//做好标记量
long size=channel.size();
int pos=0;
int offset=4096;
long curnset=0;
long counts=0;
//循环写
while (pos < size){
//把文件直接读取到socket chanel中,返回文件大小
curnset=channel.transferTo(pos,4096,sc);
pos+=offset;
counts+=curnset;
}
//关闭
channel.close();
sc.close();
//打印传输字节数
System.out.println(counts);
//打印时间
System.out.println("bytes send--"+counts+"and totaltime--"+(System.currentTimeMillis() - start));
}private final int port;
public EchoServer(int port) {
this.port = port;
}
public void start() throws Exception{
EventLoopGroup eventLoopGroup=null;
try {
//server端引导类
ServerBootstrap serverBootstrap = new ServerBootstrap();
//连接池处理数据
eventLoopGroup = new NioEventLoopGroup();
//装配bootstrap
serverBootstrap.group(eventLoopGroup)
.channel(NioServerSocketChannel.class)//指定通道类型为NioServerSocketChannel,一种异步模式,OIO阻塞模式为OioServerSocketChannel
.localAddress("localhost",port) //设置InetSocketAddress让服务器监听某个端口已等待客户端连接
.childHandler(new ChannelInitializer<Channel>() {//设置childHandler执行所有的连接请求
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new EchoServerHandler());//注册handler
}
});
ChannelFuture channelFuture = serverBootstrap.bind().sync();
System.out.println("开始监听,端口为:" + channelFuture.channel().localAddress());
channelFuture.channel().closeFuture().sync();
}finally {
if (eventLoopGroup != null) {
eventLoopGroup.shutdownGracefully().sync();
}
}
}
public static void main(String[] args) throws Exception {
new EchoServer(20000).start();
}public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("server 读取数据......");
//读取数据
ByteBuf buf =(ByteBuf)msg;
byte[] req=new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("接收客户端数据:"+body);
//向客户端写数据
System.out.println("server向client发送数据");
String currentTime = new Date(System.currentTimeMillis()).toString();
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("server 读取数据完毕..");
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}private final String host;
private final int port;
public EchoClient(String host, int port) {
this.host = host;
this.port = port;
}
public void start() throws Exception{
EventLoopGroup eventLoopGroup=null;
try {
//客户端引导类
Bootstrap bootstrap = new Bootstrap();
//EventLoopGroup 可以理解为一个线程池,这个线程池用来处理数据,发送数据,接收数据
eventLoopGroup=new NioEventLoopGroup();
bootstrap.group(eventLoopGroup)//多线程处理
.channel(NioSocketChannel.class)//指定通道类型为NioServerSocketChannel,一种异步模式,OIO阻塞模式为OioServerSocketChannel
.remoteAddress(new InetSocketAddress(host,port))//地址
.handler(new ChannelInitializer<SocketChannel>() {//业务处理类
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());//注册handler
}
});
// 链接服务器
ChannelFuture channelFuture = bootstrap.connect().sync();
channelFuture.channel().closeFuture().sync();
}finally {
if (eventLoopGroup != null) {
eventLoopGroup.shutdownGracefully().sync();
}
}
}
public static void main(String[] args) throws Exception {
new EchoClient("localhost", 20000).start();
}public class EchoClientHandler extends SimpleChannelInboundHandler{
//客户端连接服务请后被调用
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("客户端连接");
String time=new Date().toString();
String req2=time+" QUERY TIME ORDER";
byte[] req=req2.getBytes();//消息
ByteBuf buffer = Unpooled.buffer(req.length);
buffer.writeBytes(req);//发送
ctx.writeAndFlush(buffer);//flush
}
// 发生异常时被调用
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("client exceptionCaught...");
//释放资源
ctx.close();
}
//从服务器接收到数据后调用
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("client 读取server数据..");
//服务端返回消息后
ByteBuf buf=(ByteBuf)msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("服务端数据为:"+body);
}
}