简体   繁体   中英

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.

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();

    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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