如何从路径末尾向路径开头发送消息,即从生产者端点发送到消费者端点?
我的生产者端点是一个套接字服务器,偶尔会有一个连接的客户端发送一条需要转发到另一端的消息。
from("socks:client:localhost:3456").to("socks:server:localhost:3333");
我在messageReceived
中遇到以下代码:
public class SocksProducer extends DefaultAsyncProducer {
private List<Channel> connectedClients = new CopyOnWriteArrayList<Channel>();
public SocksProducer(SocksEndpoint socksEndpoint, int port) {
super(socksEndpoint);
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.receiveBufferSize", 1048576);
bootstrap.setOption("child.sendBufferSize", 1048576);
bootstrap.getPipeline().addLast("encode", new StringEncoder());
bootstrap.getPipeline().addLast("decoder", new StringDecoder());
bootstrap.getPipeline().addLast("echo", new ClientDataHandler());
bootstrap.bind(new InetSocketAddress(port));
}
@Override
public boolean process(Exchange exchange, AsyncCallback arg1) {
String msg = exchange.getIn().getBody(String.class);
connectedClients.forEach((channel) -> channel.write(msg));
return true;
}
class ClientDataHandler extends SimpleChannelUpstreamHandler {
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
super.channelClosed(ctx, e);
connectedClients.remove(ctx.getChannel());
}
@Override
public void channelConnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
super.channelConnected(ctx, e);
connectedClients.add(ctx.getChannel());
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
Exchange exchange = getEndpoint().createExchange();
exchange.getIn().setBody(e.getMessage());
// try {
// getProcessor().process(exchange);
// } finally {
// // log exception if an exception occurred and was not handled
// if (exchange.getException() != null) {
// getExceptionHandler().handleException(
// "Error processing exchange", exchange,
// exchange.getException());
// }
// }
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
// Close the connection when an exception is raised.
e.getCause().printStackTrace();
log.error("", e.getCause());
e.getChannel().close();
}
}
}