Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java.net.Socket中的Apache Mina服务器和客户端_Java_Sockets_Nio_Apache Mina - Fatal编程技术网

java.net.Socket中的Apache Mina服务器和客户端

java.net.Socket中的Apache Mina服务器和客户端,java,sockets,nio,apache-mina,Java,Sockets,Nio,Apache Mina,我的应用程序将数据发送到Apache Mina服务器,该服务器使用以下配置进行侦听 IoAcceptor acceptor = new NioSocketAcceptor(); acceptor.getFilterChain().addLast( "logger", new LoggingFilter() ); //acceptor.getFilterChain().addLast( "logger1", new TempFilter());

我的应用程序将数据发送到Apache Mina服务器,该服务器使用以下配置进行侦听


        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) );
这是我用net.Socket编写的客户端代码


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


oStrm.write(byteSendBuffer);
oStrm.flush();
尽管记录器显示收到的消息, 永远不会调用服务器处理程序的
messagereceived()
。。请尝试以下操作:

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

    }
}

您正在使用TextLineCodeFactory作为协议编解码器,它希望您的消息以line delimeter结尾。在unix上是“\n”,在windows上是“\r\n”,可以通过Java上的
System.lineSeparator()
获得

当然,TextLineCodeFactory的可用性取决于消息的内容。如果邮件内容中包含行delimeter字符,则不能使用TextLineCodeFactory。在这种情况下,您可能希望实现自己的编解码器工厂,使用特殊字符作为delimeter、固定大小的消息或结构