![](/img/trans.png)
[英]Apache mina SocketAcceptor and java.net.Socket communication
[英]Apache Mina Server and client in java.net.Socket
我的應用程序將數據發送到Apache Mina Server,該服務器使用以下配置進行偵聽。
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();
雖然記錄器顯示消息已收到, messageRecieved()
不調用服務器處理程序的messageRecieved()
..請hlp。
嘗試這個:
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();
}
}
您正在使用TextLineCodecFactory作為協議編解碼器,期望您的消息以行分隔符結束。 這是unix上的“\\ n”,Windows上的“\\ r \\ n”,可以通過Java上的System.lineSeparator()
獲取。
當然TextLineCodecFactory的可用性取決於你的消息的內容。 如果您的消息在其內容中包含行分隔符,則不能使用TextLineCodecFactory。 在這種情況下,您可能希望實現自己的編解碼器工廠,該工廠使用特殊字符作為分隔符,固定大小的消息或類型長度值結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.