Java NIO框架Netty教程(三) 字符串消息收发

Java NIO框架Netty教程(三) 字符串消息收发 标签:socket col har on

Java NIO框架Netty教程(三) 字符串消息收发

标签:socketcolharoneexcept.comregbootstraptext

了解了Netty的基本概念(http://www.it165.net/pro/html/201207/3173.html),开发起来应该会顺手很多。 在“Hello World(http://www.it165.net/pro/html/201207/3142.html)”代码中,我们只是在完成绑定的时候,在各自的本地打印了简单的信息,并没有客户端和服务端的消息传递。这个肯定是最基本的功能。在上代码之前,先补充一个Netty中重要的概念,ChannelBuffer.

ChannelBuffer

Netty中的消息传递,都必须以字节的形式,以ChannelBuffer为载体传递。简单的说,就是你想直接写个字符串过去,对不起,抛异常。虽然,Netty定义的writer的接口参数是Object的,这可能也是会给新上手的朋友容易造成误会的地方。Netty源码中,是这样判断的:

view sourceprint?

01.SendBuffer acquire(Object message) {
02.if(messageinstanceofChannelBuffer) {
03.returnacquire((ChannelBuffer) message);
04.}elseif(messageinstanceofFileRegion) {
05.returnacquire((FileRegion) message);
06.}
07.
08.thrownewIllegalArgumentException(
09.\”unsupported message type: \”+ message.getClass());
10.}

所以,我们要想传递字符串,那么就必须转换成ChannelBuffer。明确了这一点,接下来我们上代码:

view sourceprint?

01./**
02.* @author lihzh
03.* @alia>04.* @bloghttp://www.coderli.com
05.*/
06.publicclassMessageServer {
07.
08.publicstaticvoidmain(String args[]) {
09.// Server服务启动器
10.ServerBootstrap bootstrap =newServerBootstrap(

作者: liuzhihao

为您推荐

返回顶部