![](/img/trans.png)
[英]How to send ISO message Object from client to Netty server in java
[英]netty 4 How to send message from server
如何從服務器本身發送消息,而不是從MessageHandlers發送消息? 我知道InetSocketAddress,我從MessageHandler存儲它,但我看不到任何直接使用套接字的方法。
例如:
public class QuoteOfTheMomentServer {
private final int port;
public QuoteOfTheMomentServer(int port) {
this.port = port;
}
Bootstrap b;
public void run() throws Exception {
b = new Bootstrap();
try {
b.group(new NioEventLoopGroup())
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new QuoteOfTheMomentServerHandler());
b.bind(port).sync().channel().closeFuture().await();
} finally {
b.shutdown();
}
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new QuoteOfTheMomentServer(port).run();
}
}
我該如何添加方法呢
public void sendMessage(ByteBuf msg, InetSocketAddr addr) {
b.send(msg, addr);
}
只需存儲對頻道的引用並使用:
channel.write(new DatagramPacket(
Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
new InetSocketAddress(ip, port)));
您可以從任何線程調用channel.write,也可以從處理程序外部調用
保存ChannelHandlerContext,並使用它將數據發送到客戶端
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.