简体   繁体   English

使用 Apache Mina 通过 UDP 将数据发送回客户端

[英]Send data back to client with UDP using Apache Mina

I am using Apache Mina to create a server to accept UDP Client requests.我正在使用 Apache Mina 创建一个服务器来接受 UDP 客户端请求。 I have read the Official documentation provided by Apache Mina regarding UDP Server & UDP Client .我已阅读 Apache Mina 提供的有关UDP Server & UDP Client的官方文档。 However, I wished to know when the server receives a message, can I write back to the UDP Client using the same session(I know UDP is connectionless at Network Layer, however I can get the IP and PORT of the remote host at Application Layer) such that UDP Client receives a message.但是,我想知道服务器何时收到消息,我可以使用相同的会话写回 UDP 客户端吗(我知道 UDP 在网络层是无连接的,但是我可以在远程主机的应用程序层获得 ZA12A3079E14CED46E69BA52B8 和 PORT ) 这样 UDP 客户端就会收到一条消息。 I know this is possible is TCP but am a little confused about UDP.我知道这可能是 TCP 但对 UDP 有点困惑。 I know this may not exactly be Java based but more Network Layer based question.我知道这可能不完全是基于 Java 而是更多基于网络层的问题。 Would appreciate if somebody could clear this for me.如果有人能为我解决这个问题,我将不胜感激。

@Override
    public void messageReceived(IoSession session, Object message) throws Exception {

            for (int i = 0; i < session.getService().getManagedSessions().values().toArray().length; i++) {

                IoSession aSession=(IoSession) session.getService().getManagedSessions().values().toArray()[i];
                aSession.write("Any Message");
            }



    }

Try this your handler class试试这个你的处理程序 class

@Override
public void messageReceived(IoSession session, Object message) throws Exception {
        // response every time get data 
        byte[] b = "Received".getBytes();
        final IoBuffer responsebuffer = IoBuffer.allocate(b.length);
        responsebuffer.put(b);
        responsebuffer.flip();
        session.write(responsebuffer);
        SocketAddress remoteAddress = session.getRemoteAddress();

        if (message instanceof IoBuffer) {
            IoBuffer buffer = (IoBuffer) message;
            final CharsetDecoder decoder = getCharsetDecoder(session);
            String receivedMsg = buffer.getString(decoder);
            String data = remoteAddress + " Received: " + receivedMsg;
            server.append(data);
        }

    }

I got the answer to the same and thought i would share.我得到了相同的答案,并认为我会分享。

UDP is connectionless however I can use the same session which I have in Apache Mina to write to the session. ZF5EF036B4D8B630721EFE23489FBC9Z是无连接的,但是我可以使用相同的Z21D6F40CFB511982E424E250A95757Z,我在ZE9713AE04AAE04A810D4156F36F33DD9D9D9D9D9D9D9D9D9D9D9D9DD9DD9DD9D9DD9DD9DD9DD9DD9DD9DD9DD9DD9DERAPANEANAPARENIS IN I tried it as a sample also and it worked.我也将其作为样本进行了尝试,并且有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM