最近一段时间一直研究聊天程序,学习了nio的知识,以后会和大家分享的,今天写了一个可以运行看到结果的netty helloworld程序,这个程序虽然简单,但从这个程序可以知道netty的运行流程,希望对初学者有所帮助。
第一步:建立一个maven项目,或者读者可以自己导入netty依赖包
1. <dependency>
2. <groupId>io.netty</groupId>
3. <artifactId>netty</artifactId>
4. 3.5.6.Final</version>
5. </dependency>
现在netty 4.0已经出来了,因为3.x版本的资料比较多有利于学习,先从3.x开始了,以后会继续出4.x的学习笔记的,呵呵,上程序了
第二步:复制下面代码到项目中
1. package com.my.day1;
2.
3. import java.net.InetSocketAddress;
4. import java.util.concurrent.Executors;
5.
6. import org.jboss.netty.bootstrap.ServerBootstrap;
7. import org.jboss.netty.channel.Channel;
8. import org.jboss.netty.channel.ChannelHandlerContext;
9. import org.jboss.netty.channel.ChannelPipeline;
10. import org.jboss.netty.channel.ChannelStateEvent;
11. import org.jboss.netty.channel.MessageEvent;
12. import org.jboss.netty.channel.SimpleChannelHandler;
13. import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
14. import org.jboss.netty.handler.codec.string.StringDecoder;
15. import org.jboss.netty.handler.codec.string.StringEncoder;
16.
17. /**
18. * @Title: NettyDemo.java
19. * @Package com.my.day1
20. * @Description: 一个类完整运行netty,运行就能看到结果
21. * @author jimmy lovelyxuehanxin@163.com
22. * @date 2013-4-16 下午9:38:29
23. */
24. public class NettyDemo {
25. public static void main(String[] args) {
26. new NioServer();
27. }
28. }
29.
30. class NioServer{
31. ServerBootstrap bootstrap;
32. Channel parentChannel;
33. InetSocketAddress localAddress;
34. new MyChannelHandler();
35. public NioServer(){
36. new ServerBootstrap(new NioServerSocketChannelFactory(
37. Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
38.
39.
40. ChannelPipeline pineline = bootstrap.getPipeline();
41. // String格式字符串解码写的时候都会经过这个过滤器处理
42. "encode", new StringEncoder());
43. // 接受信息的时候会被处理
44. "decode", new StringDecoder());
45. // 自定义处理类,我们的业务一般从这个类开始
46. "servercnfactory", channelHandler);
47. new InetSocketAddress(8080));
48. }
49.
50. }
51. // 处理channel中的数据,SimpleChannelHandler帮我们实现好了很多有用户的方法这里就只重写了几个方法
52. class MyChannelHandler extends SimpleChannelHandler{
53.
54. // netty默认信息接受入口
55. @Override
56. public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
57. throws Exception {
58. "接受到的信息" + e.getMessage());
59. // 返回信息可以在dos对话框中看到自己输的内容
60. e.getChannel().write(e.getMessage());
61. super.messageReceived(ctx, e);
62. }
63.
64. @Override
65. public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
66. throws Exception {
67. "channel Connected......");
68. super.channelConnected(ctx, e);
69. }
70.
71. @Override
72. public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
73. throws Exception {
74. "channelClosed");
75. super.channelClosed(ctx, e);
76. }
77.
78. }
第三步:运行上面的代码,cmd打开dos窗口输入telnet 127.0.0.1 8080 输入内容 程序就可以打印你输入的内容并且可以在dos命令框里打印出你输入的内容。
总结:这个列子很简单,可以清楚程序怎么运行的,对理解netty很有帮助