作为我协议的一部分,我希望客户端在建立新连接时发送其版本号。我希望在管道中的单独处理程序中完成此操作,因此请耐心等待,因为这可能是一个相当基本的问题,但我不知道该怎么做。另一件事是我希望能够通过连接(管道)来回发送 POJO。我也很想添加一个身份验证处理程序。无论如何,现在我遇到了某种错误,我很确定这是因为版本检查没有从管道中正确消化。
基本上,我下面的代码设置为发送“Hello World”,在建立连接后检查版本后服务器打印出来。至少在理论上,实际上这并不完全有效;)
目前我有:
客户端.java
public static void main(String[] args)
{
...
// Set up the pipeline factory.
bootstrap.setPipelineFactory(new ChannelPipelineFactory()
{
@Override
public ChannelPipeline getPipeline() throws Exception
{
return Channels.pipeline(
new ObjectEncoder(),
new ObjectDecoder(),
new VersionClientHandler(),
new BusinessLogicClientHandler());
}
});
...
// The idea is that it will all be request and response. Much like http but with pojo's.
ChannelFuture lastWriteFuture = channel.write("Hello world".getBytes());
if (lastWriteFuture != null)
{
System.out.println("waiting for message to be sent");
lastWriteFuture.awaitUninterruptibly();
}
...
}
版本客户端处理程序.java
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
{
ChannelBuffer versionBuffer = ChannelBuffers.buffer(VERSION_STRING_LENGTH);
versionBuffer.writeBytes("v123.45a".getBytes());
// If I understand correctly, the next line says use the rest of the stream to do what you need to the next Handler in the pipeline?
Channels.write(ctx, e.getFuture(), versionBuffer);
}
BusinessLogicClientHandler.java
Not really doing anything at this point. Should it?
服务器.java
public static void main(String[] args)
{
...
public ChannelPipeline getPipeline() throws Exception
{
return Channels.pipeline(
new ObjectEncoder(),
new ObjectDecoder(),
new VersionServerHandler(),
new BusinessLogicServerHandler());
}
...
}
版本服务器处理程序.java
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
{
ChannelBuffer versionBuffer = ChannelBuffers.buffer(VERSION_NUMBER_MAX_SIZE);
System.out.println("isReadable - messageReceived: " + versionBuffer.readable()); // returns false???
// Basically I want to read it and confirm the client and server versions match.
// And if the match fails either send a message or throw an exception
// How do I also pass on the stream to the next Handler?
}
业务逻辑服务器处理程序.java
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
{
e.getMessage();
byte[] message = (byte[])e.getMessage(); // "Hello World" in byte[] from Client.java
}
所以基本上我想要的是在作为通信协议的一部分连接通道时传递和验证版本号。所有这些都是在幕后自动完成的。同样,我很想以这种方式通过身份验证机制。
我确实看到了一些看起来有点像我想对安全聊天示例执行的代码,但我无法真正弄清楚。任何有关如何设置此代码的帮助将不胜感激。我知道我可以在一个大型处理程序中完成所有工作,但这就是管道的重点,将其分解为合乎逻辑的单元。