Netty是一个非租塞的异步通信框架,它是机遇NIO开发的,NIO的全称是NoneBlocking IO,非阻塞IO,区别于BIO,BIO的全称是Blocking IO,阻塞IO,非阻塞比阻塞式的编程更加节省服务器资源,下面使用netty编写一个socket客户端与服务器端,算是对Netty的Hello World入门吧!
第一步:使用Maven导入netty相关的jar包,代码如下:
org.jboss.marshalling
jboss-marshalling
2.0.5.Final
org.jboss.marshalling
jboss-marshalling-serial
1.3.0.CR9
test
io.netty
netty-all
4.1.23.Final
注意:没有第二个jboss-marshalling-serial包客户端可能无法接收到消息,所以最好导入进来。
第二步:使用jboss的marshalling来对发送和接收的socket数据进行编码解码操作,代码如下:public class MarshallingCodeCFactory {
//解码
public static MarshallingDecoder buildMarshallingDecoder() {
final MarshallerFactory factory = Marshalling.getProvidedMarshallerFactory("serial");
final MarshallingConfiguration configuration = new MarshallingConfiguration();
configuration.setVersion(5);
UnmarshallerProvider provider = new DefaultUnmarshallerProvider(factory, configuration);
MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024*1024);
return decoder;
}
//编码
public static MarshallingEncoder buildMarshallingEncoder() {
final MarshallerFactory factory = Marshalling.getProv