服务端代码:

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. dfs Gym - 100989L

    AbdelKader enjoys math. He feels very frustrated whenever he sees an incorrect equation and so he tr ...

  2. PRO*C 函数事例 3 -- 游标使用

    1.Oracle中的游标    Oracle使用两种游标: 显式游标和隐式游标. 不管语句返回多少条记录, Oracle为每条使用的SQL语句隐式地定义一个游标. Oracle为每个DELETE , ...

  3. python基础——重访类型分类

    python基础--重访类型分类 对象根据分类来共享操作:例如,字符串.列表和元组都共享诸如合并.长度和索引等序列操作. 只有可变对象(列表.字典和集合)可以原处修改:我们不能原处修改数字,字符串.元 ...

  4. 我所认识的XPath

    实例demo 测试demo所需要xml测试数据 <?xml version="1.0" encoding="iso-8859-1"?> <bo ...

  5. iOS笔记054 - 核心动画

    注意事项 :locationInView和translationInView // 返回相对于控件自身内部触摸点的位置 [pan locationInView:self]; // 返回两个触摸点之间的 ...

  6. 【个人训练】(POJ1837)Balance

    这几天抓住国庆的黄金时间(因为没有女朋友,天天刷题emmmm 其实还在肝少前还要捞秋刀鱼) ,重点攻克掉几个基本的地方:搜索.dp.图论.这几天的题目应该就是这些范围. 题意 原题的意思大概是这样的, ...

  7. Selenium驱动Chrome浏览器

    import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome ...

  8. json与python解析

    1.json.dumps     将 Python 对象编码成 JSON 字符串   json.loads      将已编码的 JSON 字符串解码为 Python 对象 2.json.dump() ...

  9. kafka java动态获取topic并动态创建消费者

    1.获取所有topic package com.example.demo; import java.io.IOException; import java.util.List; import org. ...

  10. 输出不重复的质因数(C++)

    [问题描述] 从键盘上输入一个大于 1 的正整数,输出它所有不等的质因数.(什么是质因数?既是质数,又是因数) [代码展示] # include<iostream>using namesp ...