Send data back to client with UDP using Apache Mina
I am using Apache Mina to create a server to accept UDP Client requests. I have read the Official documentation pro开发者_StackOverflow社区vided by Apache Mina regarding 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. I know this is possible is TCP but am a little confused about UDP. I know this may not exactly be Java based but more Network Layer based question. Would appreciate if somebody could clear this for me.
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. I tried it as a sample also and it worked.
@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
@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);
}
}
精彩评论