服务端代码:

package com.lsp.netty;

/**
* @author lishupeng
* @create 2017-05-27 下午 3:48
**/
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder; public class Socket {
public static void main(String[] args) throws InterruptedException {
//1.第一个线程组是用于接收Client端连接的
EventLoopGroup bossGroup = new NioEventLoopGroup();
//2.第二个线程组是用于实际的业务处理的
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);//绑定两个线程池
b.channel(NioServerSocketChannel.class);//指定NIO的模式,如果是客户端就是NioSocketChannel
b.option(ChannelOption.SO_BACKLOG, 1024);//TCP的缓冲区设置
b.option(ChannelOption.SO_SNDBUF, 32*1024);//设置发送缓冲的大小
b.option(ChannelOption.SO_RCVBUF, 32*1024);//设置接收缓冲区大小
b.option(ChannelOption.SO_KEEPALIVE, true);//保持连续
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());//拆包粘包定义结束字符串(第一种解决方案)
sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));//在管道中加入结束字符串
// sc.pipeline().addLast(new FixedLengthFrameDecoder(200));第二种定长
sc.pipeline().addLast(new StringDecoder());//定义接收类型为字符串把ByteBuf转成String
sc.pipeline().addLast(new ServertHandler());//在这里配置具体数据接收方法的处理
}
});
ChannelFuture future = b.bind(8765).sync();//绑定端口
future.channel().closeFuture().sync();//等待关闭(程序阻塞在这里等待客户端请求)
bossGroup.shutdownGracefully();//关闭线程
workerGroup.shutdownGracefully();//关闭线程
}
}
package com.lsp.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; /**
* @author lishupeng
* @create 2017-05-27 下午 3:48
**/
public class ServertHandler extends ChannelHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String body = (String) msg;
System.out.println("server"+body);//前面已经定义了接收为字符串,这里直接接收字符串就可以
//服务端给客户端的响应
String response= " hi client!$_";//发送的数据以定义结束的字符串结尾
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));//发送必须还是ByteBuf类型
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
} }

客户端代码:

package com.lsp.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder; /**
* @author lishupeng
* @create 2017-05-27 下午 3:48
**/
public class Client {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup worker = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(worker)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));
sc.pipeline().addLast(new StringDecoder());
sc.pipeline().addLast(new ClientHandler());
}
});
ChannelFuture f=b.connect("127.0.0.1",8765).sync();
f.channel().writeAndFlush(Unpooled.copiedBuffer(" hi server2$_".getBytes()));
f.channel().writeAndFlush(Unpooled.copiedBuffer(" hi server3$_".getBytes()));
f.channel().writeAndFlush(Unpooled.copiedBuffer(" hi server4$_".getBytes()));
f.channel().closeFuture().sync();
worker.shutdownGracefully();
} }
package com.lsp.netty;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil; /**
* @author lishupeng
* @create 2017-05-27 下午 3:49
**/
public class ClientHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
System.out.println("client"+msg.toString());
} finally {
ReferenceCountUtil.release(msg);//释放缓冲区
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}

netty入门代码学习的更多相关文章

  1. TensorFlow(1)注解入门代码

    学习当然要从官方的入门文档开始. 但是这篇入门对于从0开始的初学者似乎有些困难,尤其是对于神经网络知识还是一知半解的. 敲完理解一遍还是懵逼. TensorFlow经典入门代码学习备注如下. impo ...

  2. Java网络编程 -- Netty入门

    Netty简介 Netty是一个高性能,高可扩展性的异步事件驱动的网络应用程序框架,它极大的简化了TCP和UDP客户端和服务器端网络开发.它是一个NIO框架,对Java NIO进行了良好的封装.作为一 ...

  3. Java IO学习笔记八:Netty入门

    作者:Grey 原文地址:Java IO学习笔记八:Netty入门 多路复用多线程方式还是有点麻烦,Netty帮我们做了封装,大大简化了编码的复杂度,接下来熟悉一下netty的基本使用. Netty+ ...

  4. netty权威指南学习笔记二——netty入门应用

    经过了前面的NIO基础知识准备,我们已经对NIO有了较大了解,现在就进入netty的实际应用中来看看吧.重点体会整个过程. 按照权威指南写程序的过程中,发现一些问题:当我们在定义handler继承Ch ...

  5. (入门篇 NettyNIO开发指南)第三章-Netty入门应用

    作为Netty的第一个应用程序,我们依然以第2章的时间服务器为例进行开发,通过Netty版本的时间服务报的开发,让初学者尽快学到如何搭建Netty开发环境和!运行Netty应用程序. 如果你已经熟悉N ...

  6. Netty入门之HelloWorld

    Netty系列入门之HelloWorld(一) 一. 简介 Netty is a NIO client server framework which enables quick and easy de ...

  7. 【Netty源码学习】ChannelPipeline(一)

    ChannelPipeline类似于一个管道,管道中存放的是一系列对读取数据进行业务操作的ChannelHandler. 1.ChannelPipeline的结构图: 在之前的博客[Netty源码学习 ...

  8. Netty入门与实战教程总结分享

    前言:都说Netty是Java程序员必须要掌握的一项技能,带着不止要知其然还要知其所以然的目的,在慕课上找了一个学习Netty源码的教程,看了几章后着实有点懵逼.虽然用过Netty,并且在自己的个人网 ...

  9. Webpack新手入门教程(学习笔记)

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; text-align: center; font: 30.0px Helvetica; color: #000000 } ...

随机推荐

  1. kafka重置offset

    kafka重置offset   1.删除zookeeper上节点信息 打开client :./zkCli.sh -server 127.0.0.1:12181 删除consumer:rmr /cons ...

  2. 什么是OSS/BSS(电信业务)

    电信业务运营支持系统(BOSS),面对客户是统一的:面对电信运营商,它融合了业务支撑系统(BSS)与运营支撑系统(OSS),是一个综合的业务运营和管理平台,同时也是真正融合了传统IP数据业务与移动增值 ...

  3. A problem occurred evaluating project ':'. > ASCII

    项目编译出错: 错误信息如下: FAILURE: Build failed with an exception. * Where: Build file 'F:\git\i***\build.grad ...

  4. linux手动安装flash插件

    下载好之后,将解压的文件 1,将libflashplayer.so拷到firefox的插件目录/usr/lib/firefox/browser/plugin/ sudo cp libflashplay ...

  5. 「日常训练」Mike and Feet(Codeforces Round #305 Div. 2 D)

    题意 (Codeforces 548D) 对一个有$n$个数的数列,我们要求其连续$x(1\le x\le n)$(对于每个$x$,这样的连续group有若干个)的最小数的最大值. 分析 这是一道用了 ...

  6. 机器学习性能指标精确率、召回率、F1值、ROC、PRC与AUC--周振洋

    机器学习性能指标精确率.召回率.F1值.ROC.PRC与AUC 精确率.召回率.F1.AUC和ROC曲线都是评价模型好坏的指标,那么它们之间有什么不同,又有什么联系呢.下面让我们分别来看一下这几个指标 ...

  7. 3.爬虫 urlib库讲解 总结

    urllib库的总结: 用ProcessOn(安利这个软件,够用了)根据前面的几节内容做了个思维导图. urllib库一共有四个模块: request:它是最基本的模块,可以用来模拟发送请求 erro ...

  8. LeetCode 237 ——删除链表中的结点

    1. 题目 2. 解答 因为给定的只有一个待删除的结点指针,我们并不知道其前面结点,所以需要将待删除结点后面的结点值复制到前面结点去,然后指向其后的第二个结点即可. /** * Definition ...

  9. Java开发JDBC连接数据库

    Java开发JDBC连接数据库 创建一个以JDBC连接数据库的程序,包含6个步骤: JDBC五部曲1.加载驱动2.获得链接3.获取statement对象 4.执行SQL语句5.产生resultset对 ...

  10. winform timer时间间隔小于执行时间

    如果SetTimer的时间间隔为t,其响应事件OnTimer代码执行一遍的时间为T,且T>t.这样,一次未执行完毕,下一次定时到,这时候程序会如何执行? 可能的情况:1.丢弃还未执行的代码,开始 ...