高分求救:如何用 ServerSocketChannel & SocketChannel做的一个接收客户端的数据包?(在线)
1、客户端程序可以连上来,但发送一次之后,发送第2次,服务器就出问题了,主要是在run()方法中的while (selector.select() > 0)这句上,本来selector.select()应该是阻塞的,但第2次发送后,就不阻塞了,立刻返回,而且为false。请问这是为什么?
2、连第二个客户端的时候,程序也没有检测到,key.isAcceptable()始终为false,是怎么回事?
代码如下:
public void init(int portNumber) throws Exception{
//分配一个ServerSockerChannel
serverChannel = ServerSocketChannel.open();
//从ServerSocketChannel里获得一个对应的Socket
serverSocket = serverChannel.socket();
//生成一个Selector
selector = Selector.open();
//把socket绑定到端口上
serverSocket.bind(new InetSocketAddress(portNumber));
//serverChannel为非bolck
serverChannel.configureBlocking(false);
//通过Selector注册ServerSocketChannel
//serverChannel.register(selector,SelectionKey.OP_ACCEPT);
serverChannel.register(selector,SelectionKey.OP_ACCEPT);
}
protected void registerChannel(Selector selector,SelectableChannel channel,int ops) throws Exception{
if (channel == null){
return;
}
channel.configureBlocking(false);
channel.register(selector,ops);
}
protected void processData(SelectionKey key) throws Exception{
SocketChannel socketChannel = (SocketChannel)key.channel();
USSDMessage message = (USSDMessage)messageFactory.createMessage( " ") ;
USSDEvent event = null;
int count;
buffer.clear();
//读取所有的数据
while((count = socketChannel.read(buffer)) > 0){
System.out.println( "count: "+count);
buffer.flip();
while(buffer.hasRemaining()){
message.buildMessageFromBuffer(buffer);
if(message != null){
int intCmdId = message.getCmdId();
if(intCmdId == Constant.USSD_MESSAGE_COMMAND_SURVEILLANCE_REQ)
{
event = new USSDEvent(buffer);
this.applicationContext.publishEvent(event);
}
message = this.resetUSSDMessage(message);
buffer.clear();
ByteBuffer newBuffer = buffer.slice() ;
message.appendToBuffer(newBuffer);
System.out.println( "buffer write to socketChannel begin! ");
// message.buildMessageFromBuffer(buffer);
socketChannel.write(buffer); //在socket里写数据
System.out.println( "buffer write to socketChannel end! ");
}
}
buffer.clear(); //清空buffer
// count = -1;
// break;
}
if(count < 0){
//count <0,说明已经读取完毕
socketChannel.close();
}
}
private void processData(SocketChannel socketChannel) throws Exception
{
USSDMessage message = (USSDMessage)messageFactory.createMessage( " ") ;
USSDEvent event =