为了提供一个接口,让第三方应用跳过openfire认证,直接发送数据给用户:
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
public class EchoClient {
private final String host;
private final Integer port;
public EchoClient(String host, Integer port) {
this.host = host;
this.port = port;
}
public static void main(String[] args) {
try {
new EchoClient("127.0.0.1", 5222).start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new EchoClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect().sync();
channelFuture.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
}
}
class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception {
String strMessage;
strMessage = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
strMessage = strMessage + "<stream:stream to=\"sender@domain\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\">";
strMessage = strMessage + "<iq xmlns=\"jabber:client\" type=\"set\" id=\"123456\">";
strMessage = strMessage + "<query xmlns=\"jabber:iq:auth\">";
strMessage = strMessage + "<username>username</username><password>123456</password>";
strMessage = strMessage + "<resource>esoa</resource>";
strMessage = strMessage + "</query></iq>";
strMessage += "<message id=\"222222\" to=\"qianj@swxxzx\" from=\"admin@swxxzx\"><sendtime>2015-07-05 20:07:54</sendtime><subject>正文内容</subject><x xmlns=\"linktime.x.notice\"><id>222222</id><subject>标题</subject><body>正文内容</body><type>notice</type><url>http://www.baidu.com</url><sender>李四</sender><source>公文流转</source><time>2015-07-06 11:11:11</time><sendtime>2015-07-05 20:07:54</sendtime><desc>描述</desc><toappid>oa</toappid><fromappid>web</fromappid></x></message>";
ctx.channel().writeAndFlush(Unpooled.copiedBuffer(strMessage, Charset.defaultCharset()));
}
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
System.out.println(byteBuf.toString(Charset.defaultCharset()));
}
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
根本在于 stream:stream 和 iq。没有正式 session 的绑定,但可以通过此 session 传输 message。