gpt4 book ai didi

java - Apache mina SocketAcceptor 与 java.net.Socket 通信

转载 作者:行者123 更新时间:2023-12-01 13:04:10 24 4
gpt4 key购买 nike

我正在为 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 通信。有人能说一下哪里出了问题吗?

最佳答案

在服务器代码中替换为此LineDelimiter("$") "$"为解码分隔符

 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

关于java - Apache mina SocketAcceptor 与 java.net.Socket 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23355181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com