---
title: "说说对Netty最简单与无知的理解"
author: "bluepeer"
date: "2010-10-11T04:58:33Z"
tags: ["Mina", "Socket", "thread"]
categories: ["编程语言"]
slug: "netty"
draft: false
lastmod: "2010-10-11T04:58:33Z"
id: 780973
url: "https://bluepeer.iteye.com/blog/780973"
---

一说这种东西，不清楚的人可以吓个半死，吹了半小时冷风才醒过来。那更好。除了这个，还有MINA，CINDY...

 

开吹了：

netty一般用就一个socket服务端。当然还有其它的 。问我，我也不知道

怎么用呢？

写下方法，在Thread的start()里面调用启动就可以了。

都是个什么顺序？还有什么内容？

 

```
ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());

		ServerBootstrap bootstrap = new ServerBootstrap(factory);

		SecurityHandler handler = new SecurityHandler();

		bootstrap.getPipeline().addLast("handler", handler);

		bootstrap.bind(new InetSocketAddress(1314));
```

 

就写这内容 主要看这个SecurityHandler，这就是处理类了。一个安全验证

SecurityHandler怎么写呢？（手头上去网上下载几个例子，照抄）

先extends SimpleChannetUpstreamHandler{...}

接着重写方法，7个方法都给重写过来。

需要写内容一般都是这个：messageReceived，其它就放着吧，或者你想做些出位的个性，随你。

因为只有收到信息做检验。目标明确。

 

再吹一次风

我们再在start里面调一下一个用来做实事的方法

 

```
ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
		ServerBootstrap bootstrap = new ServerBootstrap(factory);
		MyServerHandler handler = new MyServerHandler();
		bootstrap.setPipelineFactory(new MyPipelineFactory(handler));
		bootstrap.setOption("child.tcpNoDelay", true);
		bootstrap.setOption("child.keepAlive", true);

		bootstrap.bind(new InetSocketAddress(5354));
	
```

 

感觉是有点不一样。我们也是来注意一下：

```
MyServerHandler，MyPipelineFactory
```

 

现在知道netty的代码怎么看了吧。当然不只这么简单，

```
MyServerHandler，MyPipelineFactory 里面还有很多要处理了。这里不谈。这里只说怎么用。网上有。
```