Netty筆記二(發送對象--服務端客戶端附可運行源碼)

網絡傳輸的時候採用的是流的形式,所以一個對象要發出去,並且在服務端要收到一個完整的對象,就要相應的編碼解碼的過程,這個例子向您展示netty的ObjectEncoder和ObjectDecoder編碼解碼的過程,代碼寫的比較簡單而且註釋比較多就直接用代碼了

Server 服務器端的啓動程序

package com.my.day2;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;


/**   
 * @Title: Server.java 
 * @Package com.my.day2 
 * @Description: TODO
 * @author jimmy [email protected]   
 * @date 2013-4-22 下午8:06:41 
 */
public class Server {
	public void run(){
		NioServerSocketChannelFactory channelFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
		ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
		bootstrap.setPipelineFactory(new ServerChannelPipelineFactory());
		bootstrap.setOption("tcpNoDelay", true);
		bootstrap.setOption("keepAlive", true);
		bootstrap.bind(new InetSocketAddress(8080));
	}
}

 ServerChannelPipelineFactory

 

package com.my.day2;

import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.serialization.ClassResolvers;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;

/**   
 * @Title: MyChannelFactory.java 
 * @Package com.my.day2 
 * @Description: 自定義ChannelPipelineFactory
 * @author jimmy [email protected]   
 * @date 2013-4-22 下午8:08:35 
 */
public class ServerChannelPipelineFactory implements ChannelPipelineFactory{

	@Override
	public ChannelPipeline getPipeline() throws Exception {
		
		ChannelPipeline channelPipeline = Channels.pipeline();
		/**
		 *  往流水線裏添加任務,這裏寫netty聊天的時候主要的協議解析和邏輯處理
		 *  例如1.我要對我傳送的內容進行加密解密
		 *  2.我要確定每次客戶端傳送給服務端的內容是多少
		 *  3.我要對根究客戶端發送的內容確定調用哪端業務邏輯
		 *  4.netty框架本身自帶了很多Encode和DeCode
		 */
		channelPipeline.addLast("objectDecode", new ObjectDecoder(ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
		channelPipeline.addLast("myhandler", new ServerHandler());
		return channelPipeline;
	}
}

 ServerHandler

 

 

package com.my.day2;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

/**   
 * @Title: ServerHandler.java 
 * @Package com.my.day2 
 * @Description: TODO
 * @author jimmy [email protected]   
 * @date 2013-4-22 下午8:50:46 
 */
public class ServerHandler extends SimpleChannelUpstreamHandler{

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		User user = (User) e.getMessage();
		System.out.println("form client...." + user.getName());
		super.messageReceived(ctx, e);
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		System.out.println("服務器端進來一個連接");
		super.channelConnected(ctx, e);
	}
	
	
}

 Client

 

 

package com.my.day2;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

/**   
 * @Title: Client.java 
 * @Package com.my.day2 
 * @Description: TODO
 * @author jimmy [email protected]   
 * @date 2013-4-22 下午8:57:02 
 */
public class Client {
	public void run(){
		ClientBootstrap bootstap = new ClientBootstrap();
		NioClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
		bootstap.setFactory(channelFactory);
		bootstap.setPipelineFactory(new ClientChannelPipelineFactory());
		bootstap.setOption("tcpNoDelay", true);
		bootstap.setOption("keepAlive", true);
		ChannelFuture future = bootstap.connect(new InetSocketAddress(8080));
		User user = new User();
		user.setName("xuehan");
		user.setPassword("maybe");
		future.getChannel().write(user);
		
	}
}

 ClientChannelPipelineFactory

 

 

package com.my.day2;


import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;

/**   
 * @Title: MyChannelFactory.java 
 * @Package com.my.day2 
 * @Description: 自定義ChannelPipelineFactory
 * @author jimmy [email protected]   
 * @date 2013-4-22 下午8:08:35 
 */
public class ClientChannelPipelineFactory implements ChannelPipelineFactory{

	@Override
	public ChannelPipeline getPipeline() throws Exception {
		
		ChannelPipeline channelPipeline = Channels.pipeline();
		/**
		 *  往流水線裏添加任務,這裏寫netty聊天的時候主要的協議解析和邏輯處理
		 *  例如1.我要對我傳送的內容進行加密解密
		 *  2.我要確定每次客戶端傳送給服務端的內容是多少
		 *  3.我要對根究客戶端發送的內容確定調用哪端業務邏輯
		 *  4.netty框架本身自帶了很多Encode和DeCode
		 */
		channelPipeline.addLast("objectEncode", new ObjectEncoder());
		channelPipeline.addLast("myhandler", new ClientHandler());
		return channelPipeline;
	}
}

 測試類TestServer

package com.my.day2;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelDownstreamHandler;

/**   
 * @Title: ClientHandler.java 
 * @Package com.my.day2 
 * @Description: TODO
 * @author jimmy [email protected]   
 * @date 2013-4-22 下午9:02:50 
 */
public class ClientHandler extends SimpleChannelDownstreamHandler{

	@Override
	public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		super.writeRequested(ctx, e);
	}
	

	@Override
	public void bindRequested(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		// TODO Auto-generated method stub
		super.bindRequested(ctx, e);
	}


	@Override
	public void connectRequested(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		System.out.println("客戶端請求連接");
		super.connectRequested(ctx, e);
	}
	
	
}

 測試類TestServer

package com.my.day2;
/**   
 * @Title: Test.java 
 * @Package com.my.day2 
 * @Description: TODO
 * @author jimmy [email protected]   
 * @date 2013-4-22 下午9:05:02 
 */
public class TestServer {
	public static void main(String[] args) throws InterruptedException {
		Server server = new Server();
		server.run();
		Thread.sleep(1000);
		Client client = new Client();
		client.run();
	}
}

User

package com.my.day2;

import java.io.Serializable;

/**   
 * @Title: User.java 
 * @Package com.my.day2 
 * @Description: 用於網絡傳輸的對象必須序列化否則無法傳送
 * @author jimmy [email protected]   
 * @date 2013-4-23 下午8:41:59 
 */
public class User implements Serializable{
	private static final long serialVersionUID = -7198306226394014411L;
	private String name;
	private String password;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
}

  

這是一個完整的例子用的netty的maven配置文件是

<dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty</artifactId>
      <version>3.5.6.Final</version>
 </dependency>

 附件是可以運行代碼,依賴jar文件請讀者自己去下載

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章