(1) maven 地址
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty</artifactId>
<version>3.6.3.Final</version>
</dependency>
(2) 服务端代码
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Netty服务端入门第一个小程序
*/
public class NettyServerDemo {
public static void main(String[] args) {
// 服务类
ServerBootstrap bootstrap = new ServerBootstrap();
// 初始化两个线程池
// boss线程监听端口,worker线程负责数据读写
ExecutorService boss = Executors.newCachedThreadPool();
ExecutorService worker = Executors.newCachedThreadPool();
// 设置NioServerSocketChannel工厂
bootstrap.setFactory(new NioServerSocketChannelFactory(boss,worker));
// 设置管道工厂
bootstrap.setPipelineFactory(() -> {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("encode", new StringEncoder());
pipeline.addLast("decode", new StringDecoder());
pipeline.addLast("firstHandler", new ServerChannelHandler());
return pipeline;
});
// 绑定端口
bootstrap.bind(new InetSocketAddress(20003));
System.out.println("netty服务开启了。。。。。。");
}
}
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
/**
* 服务端ChannelHandler
*/
public class ServerChannelHandler extends SimpleChannelHandler {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
super.messageReceived(ctx, e);
System.out.println("=======messageReceived=======");
/**
* 直接这么接受字符串会报错
* String msg = (String) e.getMessage();
*
* 警告: EXCEPTION, please implement com.young.socket.ch2.FirstChannelHandler.exceptionCaught() for proper handling.
* java.lang.ClassCastException: org.jboss.netty.buffer.BigEndianHeapChannelBuffer cannot be cast to java.lang.String
*
* 解决方法1:使用ChannelBuffer来接受消息,然后在转换成字符串
* ChannelBuffer recevie = (ChannelBuffer) e.getMessage();
* String msg = new String(recevie.array());
*解决方法2:在设置管道的工厂里加入字符串的编码和解码
* pipeline.addLast("encode", new StringEncoder());
* pipeline.addLast("decode", new StringDecoder());
*/
// ChannelBuffer recevie = (ChannelBuffer) e.getMessage();
// String msg = new String(recevie.array());
String msg = (String) e.getMessage();
System.out.println("接受消息 :" + msg);
// String result = "hi, yi shou dao ";
// ChannelBuffer replay = ChannelBuffers.copiedBuffer(result.getBytes());
String replay = "回复消息 :" + msg + ", thanks.....";
ctx.getChannel().write(replay);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
super.exceptionCaught(ctx, e);
System.out.println("=======exceptionCaught=======");
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelConnected(ctx, e);
System.out.println("=======channelConnected=======");
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelDisconnected(ctx, e);
System.out.println("=======channelDisconnected=======");
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
System.out.println("=======channelClosed=======");
super.channelClosed(ctx, e);
}
}
(3) 客户端代码
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Netty客户端入门第一个小程序
*/
public class NettyClientDemo {
public static void main(String[] args) {
// 服务类
ClientBootstrap bootstrap = new ClientBootstrap();
// 线程池
ExecutorService boss = Executors.newCachedThreadPool();
ExecutorService work = Executors.newCachedThreadPool();
// 设置socketChannelFactory工厂
bootstrap.setFactory(new NioClientSocketChannelFactory(boss,work));
// 设置管道工厂
bootstrap.setPipelineFactory(() -> {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("clientHandler", new ClientChannelHandler());
return pipeline;
});
// 连接服务器
ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 20003));
// 得到channel
Channel channel = connect.getChannel();
System.out.println("连上服务器。。。");
// 测试
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("请说话:");
channel.write(scanner.nextLine());
}
}
}
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
/**
* 客户端 ChannelHandler
*/
public class ClientChannelHandler extends SimpleChannelHandler {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
super.messageReceived(ctx, e);
System.out.println("==========messageReceived===============");
System.out.println(e.getMessage());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
super.exceptionCaught(ctx, e);
System.out.println("=======exceptionCaught=======");
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelConnected(ctx, e);
System.out.println("=======channelConnected=======");
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelDisconnected(ctx, e);
System.out.println("=======channelDisconnected=======");
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
System.out.println("=======channelClosed=======");
super.channelClosed(ctx, e);
}
}
netty之helloword
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 更多关于Java方面的文章,欢迎访问燕归来https://www.zhoutao123.com 官方那个给出的介绍...
- 前言 最先接触编程的知识是在大学里面,大学里面学了一些基础的知识,c语言,java语言,单片机的汇编语言等;大学毕...
- 2017年176期3D鑫鑫预测 和值:11.18 六码组六,组三:034678 五码组六,组三:03468 百位:...