Netty 服务器客户端,发送自定义消息

Netty 5 的包



服务器,四个java文件


1            SubReqServer.java

package com.test.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class SubReqServer {
	
	public void bind(int nPort) throws Exception {
		
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
				
		try{
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.option(ChannelOption.SO_BACKLOG, 100)
			.handler(new LoggingHandler(LogLevel.INFO))
			.childHandler(new ChannelInitializer(){
				@Override
				public void initChannel(SocketChannel ch) throws Exception{
					ch.pipeline()
					.addLast(
							new ObjectDecoder(1024*1024,
									ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())))
					.addLast(new ObjectEncoder())
					.addLast(new SubReqServerHandler());
				}
			});
			
			ChannelFuture f = b.bind(nPort).sync();
			System.out.println("---------------wait for connect");
			f.channel().closeFuture().sync();
		}finally {
			System.out.println("---------------wait for connect  Error!");
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
		
	
	public static void main(String[] args){
		int nPort = 5656;
		nPort = Integer.valueOf(nPort);
		System.out.println("---------------Main start");
		try {
			new SubReqServer().bind(nPort);
		} catch (Exception e) {
			System.out.println("---------------Main Error");
			e.printStackTrace();
		}
	}
}





2            SubReqServerHandler.java


package com.test.netty;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class SubReqServerHandler extends ChannelHandlerAdapter{

	@Override
	public void channelActive(ChannelHandlerContext ctx){
		System.out.println("--------------------------------handler channelActive------------");
		
//		for(int i = 0; i<10; i++){
//			SubscribeReq req = new SubscribeReq();
//			req.setAddress("深圳JJYY");
//			req.setPhoneNumber("13888886666");
//			req.setProductName("Netty Book");
//			req.setSubReqID(i);
//			req.setUserName("XXYY");
//			ctx.write(req);
//		}
//		ctx.flush();
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
		throws Exception{
		
//			SubscribeReq reqx = new SubscribeReq();
//			reqx.setAddress("*****深圳蛇口");
//			reqx.setPhoneNumber("13888886666");
//			reqx.setProductName("Netty Book");
//			reqx.setSubReqID(6666);
//			reqx.setUserName("XXYY");
//			ctx.write(reqx);
//			ctx.flush();
//		
			SubscribeResp resp = new SubscribeResp();
			resp.setnSubReqID(555);
			resp.setRespCode(0);
			resp.setDesc("-------Netty book order succeed, 3days later, sent to the designated address");
			ctx.writeAndFlush(resp);	// 反馈消息
			//ctx.write(resp);
			//ctx.flush();
		
			SubscribeReq req = (SubscribeReq)msg;   // 订购内容
			if("XXYY".equalsIgnoreCase(req.getUserName())){
				System.out.println("接收到的数据: [  " + req.toString() + "   ]");
			}
			
	}
	
	@Override
	public  void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
		System.out.println("---------------exceptionCaught 网络异常,关闭网络");
		cause.printStackTrace();
		ctx.close();
	}
}





3            SubscribeReq.java


package com.test.netty;

import java.io.Serializable;

public class SubscribeReq  implements  Serializable{
	
	private static final long nSerialVerUID = 1L;
	private int nSubReqID;
	private String strUserName;
	private String strProductName;
	private String strPhoneNumber;
	
	private String strAddr;
	
	public final int getSubReqID(){
		return nSubReqID;
	}
	
	public final void setSubReqID(int nSubReqID){
		this.nSubReqID = nSubReqID;
	}
	
	public final String getUserName(){
		return strUserName;
	}
	
	public final void setUserName(String strUserName){
		this.strUserName = strUserName;
	}
	
	public final String getProductName(){
		return strProductName;
	}
	
	public final void setProductName(String strProductName){
		this.strProductName = strProductName;
	}
	
	public final String getPhoneNumber(){
		return strPhoneNumber;
	}
	
	public final void setPhoneNumber(String strPhoneNumber){
		this.strPhoneNumber = strPhoneNumber;
	}
	
	public final String getAddress(){
		return strAddr;
	}
	
	public final void setAddress(String strAddr){
		this.strAddr = strAddr;
	}
	
	
	@Override
	public String toString(){
		return "----SubscribeReq[subReqID="+ nSubReqID + ",userName="+ strUserName
				+",productName="+strProductName+",phoneNumber="+strPhoneNumber
				+",address"+strAddr+"]";
	}
	
	
}




4            SubscribeResp.java



package com.test.netty;

import java.io.Serializable;

public class SubscribeResp implements Serializable{
	private static final long nSerialVerUID = 2L;
	
	 private int nSubReqID;

	    private int nRespCode;

	    private String strDesc;

	    public final int getnSubReqID() {
		return nSubReqID;
	    }

	    public final void setnSubReqID(int nSubReqID) {
		this.nSubReqID = nSubReqID;
	    }

	    public final int getnRespCode() {
		return nRespCode;
	    }

	    public final void setRespCode(int nRespCode) {
		this.nRespCode = nRespCode;
	    }

	    public final String getstrDesc() {
		return strDesc;
	    }

	    public final void setDesc(String strDesc) {
		this.strDesc = strDesc;
	    }

	    @Override
	    public String toString() {
		return "SubscribeResp [nSubReqID=" + nSubReqID + ", nRespCode=" + nRespCode
			+ ", strDesc=" + strDesc + "]";
	    }
}





客户端 :


SubReqClient.java

SubReqClientHand.java

SubscribeReq.java

SubscribeResp.java

和服务器一致


1            SubReqClient.java

package com.test.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class SubReqClient {

	public void connect(int nPort, String strHost) throws Exception{
		EventLoopGroup group = new NioEventLoopGroup();
		try{
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY,  true)
			.handler(new ChannelInitializer(){
				@Override
				public void initChannel(SocketChannel ch) throws Exception{
					ch.pipeline().addLast(
							new ObjectDecoder(1024, ClassResolvers
									.cacheDisabled(this.getClass().getClassLoader())));
					
					ch.pipeline().addLast(new ObjectEncoder());
					ch.pipeline().addLast(new SubReqClientHanler());
				}
			});
			
			ChannelFuture f = b.connect(strHost,  nPort).sync();
						
//			if(f.isSuccess()){
//				System.out.println("----------------main  get channel");	
//			}else{
//				System.out.println("----------------main  get channel ---f.channel().closeFuture().sync(); END!!!!");
//			}
			
			f.channel().closeFuture().sync();
			
//			f.channel().closeFuture();
		}finally{
			System.out.println("----------------main  get channel Error !!! ---------");
//			group.shutdownGracefully();
		}
	}
	
	
	public static void main(String[] args){
		int nPort = 5656;
		String strHost = "127.0.0.1";
		try {
			System.out.println("----------------main connect");
			new SubReqClient().connect(nPort, strHost);
		} catch (Exception e) {
			System.out.println("----------------main Error");
			e.printStackTrace();
		}
	}
}




2            SubReqClient.java

package com.test.netty;


import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class SubReqClientHanler extends ChannelHandlerAdapter{
	
	public SubReqClientHanler(){
		
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx){
		System.out.println("----------------handler channelActive-----准备发送十个数据-------");
		
		for(int i = 0; i<10; i++){
//			ctx.write(subReq(i));
			SubscribeReq req = new SubscribeReq();
			req.setAddress("深圳蛇口");
			req.setPhoneNumber("13888886666");
			req.setProductName("Netty Book");
			req.setSubReqID(i);
			req.setUserName("XXYY");
			ctx.write(req);
		}
		ctx.flush();
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception{
		System.out.println("--------channelRead---服务器发来的数据为:[" + msg + "]");
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx)
			throws Exception{
		System.out.println("----------------handler channelReadComplete");
		ctx.flush();
	}
	
	
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
		System.out.println("--------------------------------------------------------------------------handler exceptionCaught");
		cause.printStackTrace();
		ctx.close();
	}

}






运行结果:


服务器端:

---------------Main start
三月 30, 2016 2:47:15 下午 io.netty.handler.logging.LoggingHandler channelRegistered
信息: [id: 0x00370b13] REGISTERED
三月 30, 2016 2:47:15 下午 io.netty.handler.logging.LoggingHandler bind
信息: [id: 0x00370b13] BIND: 0.0.0.0/0.0.0.0:5656
---------------wait for connect
三月 30, 2016 2:47:15 下午 io.netty.handler.logging.LoggingHandler channelActive
信息: [id: 0x00370b13, /0:0:0:0:0:0:0:0:5656] ACTIVE
三月 30, 2016 2:47:24 下午 io.netty.handler.logging.LoggingHandler channelRead
信息: [id: 0x00370b13, /0:0:0:0:0:0:0:0:5656] RECEIVED: [id: 0x9e332f55, /127.0.0.1:56219 => /127.0.0.1:5656]
--------------------------------handler channelActive------------
接收到的数据: [  ----SubscribeReq[subReqID=0,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=1,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=2,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=3,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=4,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=5,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=6,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=7,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=8,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]
接收到的数据: [  ----SubscribeReq[subReqID=9,userName=XXYY,productName=Netty Book,phoneNumber=13888886666,address深圳蛇口]   ]



客户端:


----------------main connect
----------------handler channelActive-----准备发送十个数据-------
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
----------------handler channelReadComplete
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
--------channelRead---服务器发来的数据为:[SubscribeResp [nSubReqID=555, nRespCode=0, strDesc=-------Netty book order succeed, 3days later, sent to the designated address]]
----------------handler channelReadComplete



源码

http://download.csdn.net/detail/yulinxx/9476749

你可能感兴趣的:(Java)