代码如下。 问题是我给服务器端发送了内容,但是在服务器没有接受到内容,长度为-1,getInt获得的结果是0 ,求帮助
服务器的代码:
public void SocketChannelServer() throws Exception {
Selector seletor = Selector.open();
ServerSocketChannel serverchannel = ServerSocketChannel.open();
SocketChannel socketChannel = SocketChannel.open();
serverchannel.configureBlocking(false);
serverchannel.bind(new InetSocketAddress("127.0.0.1", 6000));
serverchannel.register(seletor, SelectionKey.OP_ACCEPT);
while (seletor.select() > 0) {// 启动服务,阻塞
Set<SelectionKey> keys = seletor.selectedKeys();
Iterator<SelectionKey> itera = keys.iterator();
while (itera.hasNext()) {
SelectionKey key = itera.next();
if (key.isAcceptable()) {
System.out.println("成功");
socketChannel = serverchannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(seletor, SelectionKey.OP_READ
| SelectionKey.OP_WRITE);
} else if (!key.isValid()) {
itera.remove();
continue;
} else if (key.isConnectable()) {
System.out.println("连接成功");
serverchannel.register(seletor, SelectionKey.OP_READ
| SelectionKey.OP_WRITE);
} else if (key.isReadable()) {
SocketChannel socketChannelNew = (SocketChannel)key.channel();
ByteBuffer bytebuffer = ByteBuffer.allocateDirect(100);
int j=socketChannelNew.read(bytebuffer);
System.out.println("长度" + j);
int y = bytebuffer.getInt();
System.out.println("读取" + y);
socketChannelNew.close();
}
else if (key.isWritable()) {
}
itera.remove();
}
}
客户端的代码:
int i=0;
SocketChannel channel=SocketChannel.open();
channel.configureBlocking(false);
InetSocketAddress remote=new InetSocketAddress("127.0.0.1",6000);
channel.connect(remote);
try {
while (!channel.finishConnect()) {
Thread.sleep(1000);
i++;
System.out.println("连接中。。。");
if (i > 5) {
break;
}
;
}
} catch (Exception e) {
System.out.println("连接失败");
return;