在同步TCP服務器的情況下,當過一個客戶端連接,我得到客戶實例的引用:有沒有什麼辦法可以讓我在客戶端連接到服務器端的服務器時創建ChannelPipeline的引用?
int serverPortNum = 9000;
socket while(true) {
ServerSocket connectionSocket = new ServerSocket(serverPortNum);
Socket dataSocket = connectionSocket.accept();
// pass this reference(dataSocket) to other part of program to read or write depending on app logic
}
現在我想用使用Netty的異步TCP服務器,以便有沒有什麼辦法,我可以得到的ChannelPipeline的參考或連接新客戶端時創建的ChannelHandler。
在客戶端我可以很容易地做到這一點:示例代碼: NioClientSocketChannelFactory ncscf =新NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()); ClientBootstrap clientBootstrap = new ClientBootstrap(ncscf);
final DummyHandler dummy = new DummyHandler();
clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(dummy);
}
});
InetAddress inetaddress = InetAddress.getByName(host);
ChannelFuturecf=clientBootstrap.connect(newInetSocketAddress(inetaddress,port));
所以每次我創建一個新的客戶時,我有新的DummyHandler參考
在服務器端:示例代碼: ServerBootstrap引導=新ServerBootstrap( 新NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new DummyServerHandler());
}
});
bootstrap.bind(new InetSocketAddress(port));
So when client request connection new DummyServerHandler object is created but i cannot get reference of this.
你看過示例服務器如echo服務器和HTTP snoop服務器嗎? – trustin 2013-03-20 07:46:03
@TustinLee:我檢查了EchoServer的例子,但是我找不到可以在哪裏找到參考。我編輯了原始問題以更詳細地解釋我的問題。 – 2013-03-20 11:39:32