我想使用Mina Framework创建UDP广播类。只是一个愚蠢的应用程序,它每隔x秒通过UDP在特定端口上发送一次相同的消息。你能告诉我MINA是否有可能吗?基于底部方法,似乎不起作用。还是基于NioAcceptor的方法是错误的?
到目前为止,我的代码(作为最小示例):
public static void main(String[] args) {
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
acceptor.setHandler(new ServerHandler());
acceptor.getFilterChain().addLast("codec", new LoggingFilter());
DatagramSessionConfig dcfg = acceptor.getSessionConfig();
dcfg.setReuseAddress(true);
dcfg.setBroadcast(true);
acceptor.bind(new InetSocketAddress("localhost", 4321));
while (true) {
acceptor.broadcast("my message.");
log.info("msg send.");
try { Thread.sleep(1000); }
catch (Exception e) {}
}
}
并且我的ServerHandler几乎为空:
public class ServerHandler extends IoHandlerAdapter {
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
log.warn("Exception", (Exception)cause);
}
public void messageSent(IoSession session, Object message) throws Exception
{
log.info("Message send: " + (String)message);
}
public void sessionClosed(IoSession session) throws Exception {
log.info("sessionClosed");
}
public void sessionCreated(IoSession session) throws Exception {
log.info("sessionCreated");
}
public void sessionOpened(IoSession session) throws Exception {
System.out.println("sessionOpened");
}
}
更新:如何设置特定的广播地址(或多个)?
对于这种UDP情况,有什么建议吗,我忘记了什么或我做错了什么?
谢谢