Apache mina SocketAcceptor和java.net.Socket通信

时间:2014-04-29 03:57:38

标签: java sockets tcp communication mina

我正在为Apache Mina Tcp服务器和java.net.Socket客户端

编写网络程序

服务器代码

    SimpleIoProcessorPool<NioSession> pool = new SimpleIoProcessorPool<NioSession>(NioProcessor.class, 20);

    SocketAcceptor acceptor = new NioSocketAcceptor(pool);
    acceptor.setReuseAddress(true);

    // Add two filters : a logger and a codec

    acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
    acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
    acceptor.setHandler( new TimeServerHandler() );

    // Configurate the buffer size and the iddle time
    acceptor.getSessionConfig().setReadBufferSize( 2048 );
    acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 1 );

    acceptor.bind( new InetSocketAddress(8001) );

我的服务器处理程序是,

public class TimeServerHandler extends IoHandlerAdapter{

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

    System.out.println("messagereceived");


    String str = message.toString();
    System.out.println(str);

    if( str.trim().equalsIgnoreCase("quit") ) {
        session.close(true);
        return;
    }

    Date date = new Date();

    System.out.println("Writing to client");

    session.write( date);
}

}

我的套接字客户端

        InetAddress inetAddress = InetAddress.getByName("localhost");
        Socket socket = new Socket(inetAddress, 8001);

        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        bufferedWriter.write("Test");
        bufferedWriter.flush();

        System.out.println(bufferedReader.readLine());

        System.out.println("Done....");

        bufferedWriter.close();
        bufferedReader.close();

问题是服务器套接字不与java.net.socket通信。 有人能说出错是什么意思......

1 个答案:

答案 0 :(得分:0)

服务器代码中的

替换为此 行分隔符(“$”)“$”是解码分隔符

 acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.DEFAULT, new LineDelimiter("$"))));

检查此链接 http://mina.apache.org/mina-project/userguide/ch9-codec-filter/ch9-codec-filter.html