我用mina框架写了一个服务器与客户端,客户端连接服务器时发一条信息,服务器接到后回复一条信息,用String发送是没有问题,但用字节数组发送时就出错了,具体如下。
客户端:
connector.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
connector.setHandler(new ClientHandler());
connector.setConnectTimeout(30);
ConnectFuture cf = connector.connect(new InetSocketAddress(127.0.0.1, 9336));
发送的代码:
String str = "test";
session.write(IoBuffer.wrap(str.getBytes()));
服务端接收的代码:
public void messageReceived(IoSession session, Object message) throws Exception {
IoBuffer ioBuffer = (IoBuffer) message;
byte[] b = new byte[ioBuffer.limit()];
ioBuffer.get(b);
String recieve = new String(b);
System.out.println(recieve);
}
当服务端没有添加new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))过滤器时,可以接收消息,但不能回复,当加了上面的过滤器后连接收都不行了,实在不懂啊,请各位帮帮忙!
客户端:
connector.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
connector.setHandler(new ClientHandler());
connector.setConnectTimeout(30);
ConnectFuture cf = connector.connect(new InetSocketAddress(127.0.0.1, 9336));
发送的代码:
String str = "test";
session.write(IoBuffer.wrap(str.getBytes()));
服务端接收的代码:
public void messageReceived(IoSession session, Object message) throws Exception {
IoBuffer ioBuffer = (IoBuffer) message;
byte[] b = new byte[ioBuffer.limit()];
ioBuffer.get(b);
String recieve = new String(b);
System.out.println(recieve);
}
当服务端没有添加new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))过滤器时,可以接收消息,但不能回复,当加了上面的过滤器后连接收都不行了,实在不懂啊,请各位帮帮忙!
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货