shahalpk
shahalpk

Reputation: 3452

Apache Mina Server and client in java.net.Socket

My application send data to Apache Mina Server which listens with the following configuration..


        IoAcceptor acceptor = new NioSocketAcceptor();
        acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
        //acceptor.getFilterChain().addLast( "logger1", new TempFilter());
        acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
        acceptor.setHandler( new TimeServerHandler() );
        acceptor.getSessionConfig().setReadBufferSize( 2048 );
        acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
        acceptor.bind( new InetSocketAddress(PORT) );

Here's my Client code written in net.Socket


OutputStream oStrm = socket.getOutputStream();
byte[] byteSendBuffer = (requests[clientNo][j]).getBytes(Charset.forName("UTF-8"));


oStrm.write(byteSendBuffer);
oStrm.flush();

Although the logger show message recieved, the server handler's messageRecieved() is never called.. Please hlp.

Upvotes: 0

Views: 1961

Answers (2)

Akdeniz
Akdeniz

Reputation: 1270

You are using TextLineCodecFactory as a protocol codec which expects your messages to end with line delimeter. That is "\n" on unix, "\r\n" on windows which can be get by System.lineSeparator() on Java.

Of course TextLineCodecFactory usability depends on your messages' content. If your message includes line delimeter character in its content, you can not use TextLineCodecFactory. In that case you may want to implement your own codec factory that use special character as delimeter ,fixed sized messages or type-length-value structure.

Upvotes: 1

Ricardo Cristian Ramirez
Ricardo Cristian Ramirez

Reputation: 1224

Try this:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class JavaNetClient {

    public static void main(String[] args) throws IOException {

        Charset charset = Charset.forName("UTF-8");
        CharsetEncoder encoder = charset.newEncoder();

        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(
                        "localhost", 1071));
        socketChannel.configureBlocking(false);
        CharBuffer charBuffer = CharBuffer.wrap("Hi\r\n");
        ByteBuffer buf = encoder.encode(charBuffer);
        socketChannel.write(buf);

        socketChannel.close();

    }
}

Upvotes: 1

Related Questions