简体   繁体   English

通过通道从客户端读取内容时,java.nio.channels.IllegalBlockingModeException

[英]java.nio.channels.IllegalBlockingModeException while reading content from client through a channel

Am very new to NIO am building a chat application i got connection in all the client but while reading content from client i got java.nio.channels.IllegalBlockingModeException . 对于NIO来说,是一个非常新的东西,我正在构建一个聊天应用程序,我在所有客户端中都建立了连接,但是在从客户端读取内容时,我却获得了java.nio.channels.IllegalBlockingModeException please help me here is the code where the exception occures. 请帮助我,这里是发生异常的代码。 while reaching while (rbc.read(b) != -1) of PrintRequest class Exception occures 同时到达PrintRequest class while (rbc.read(b) != -1)时发生

public class PrintRequest extends Thread
{

    public  PrintRequest(SocketChannel sc,int i)throws Exception
    {
        System.out.println("going to enter the try block of PrintRequest");        
        try
        {   
               System.out.println("Am in the try block of PrintRequest");    

               ReadableByteChannel rbc = Channels.newChannel(sc.socket().getInputStream()); 
               System.out.println("checking in PrintRequest 0001");
               WritableByteChannel wbc = Channels.newChannel(System.out); 
               System.out.println("checking in PrintRequest 0010");
               ByteBuffer b = ByteBuffer.allocateDirect(1024); // read 1024 bytes 
                // int numBytesRead = sc.read(b);
                 System.out.println("checking in PrintRequest 0011");
                 while (rbc.read(b) != -1) 
                 {
                     System.out.println("Am  in while loop of PrintRequest ");
                    b.flip();
                    while (b.hasRemaining())
                    { 
                         wbc.write(b);
                         System.out.println();
                    }
                    b.clear();
                 }

        }
        catch(Exception E)
        {
            System.out.println("Exception in printlnRequest  "+E);
        }                          
    }  }

my server code: 我的服务器代码:

public class Server
{

  private Selector selector;

 private ServerSocketChannel channel;

  public void listner()
   {

           try
    {
      this.selector = Selector.open();
      this.channel = ServerSocketChannel.open();
      this.channel.configureBlocking(false);
      this.channel.socket().bind(new InetSocketAddress(8888));
      this.channel.register(this.selector, 16);
    }
    catch (IOException e)
    {
      throw new RuntimeException("Could not register listener", e);
    }}


  public void non_Socket()throws Exception
    {

        try
        {
             int i=0;
             this.channel = ServerSocketChannel.open();
             this.channel.configureBlocking(false);
             this.channel.socket().bind(new InetSocketAddress(80));

            while(true)
            {

                this.selector = Selector.open();
                this.channel.register(this.selector, 16);

                Set<SelectionKey> keys = this.selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                int readyChannels = selector.select();
                if(readyChannels == 0) continue;
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
                while(keyIterator.hasNext()) 
                {
                     SelectionKey key  = keyIterator.next();
                     if(key.isAcceptable()) 
                     {
                          // a connection was accepted by a ServerSocketChannel.
                          System.out.println("a connection was accepted by a ServerSocketChannel");
                          SocketChannel sc = this.channel.accept();
                          sc.configureBlocking(false);
                          System.out.println("Received an incoming connection from " + sc.socket().getRemoteSocketAddress()); 
                          System.out.println("checking 0101");
                          // new PrintRequest(sc,i).start(); 
                          System.out.println("checking 0110");

                          if(sc == null )
                            {
                                System.out.println("Please login");
                                Thread.sleep(6000);
                            }
                          else
                          {
                                System.out.println("Last Login was successful");
                               // new PrintRequest(sc,i).start(); 
                                PrintRequest pr=new PrintRequest(sc,i);
                                new Thread(pr).start();

                          }


                     }
                     else if (key.isConnectable())
                     {
                             // a connection was established with a remote server.
                         System.out.println("a connection was established with a remote server");


                     }
                     else if (key.isWritable()) 
                     {
                        // a channel is ready for writing
                         System.out.println(" a channel is ready for writing");
                     }

                     else if (key.isReadable()) 
                     {
                        // a channel is ready for reading
                         System.out.println(" a channel is ready for Reading");
                     } 
                     System.out.println(" a channel is prepare for Reading");
                     keyIterator.remove();
                     Thread.sleep(5000);
                }

           }
        }

        catch(Exception E)
        {
            System.out.println(" Here    : "+E);
        }
        finally
              { 
                   if (channel != null) 
                   { 
                    try 
                    { 
                            channel.close(); 
                    }
                    catch (Exception e) 
                    { 
                            e.printStackTrace(); 
                    }
                   }
               }
    }


    public static void main(String [] abc) throws Exception
    {
        new Server().non_Socket();
    }}

Client side: 客户端:

public class Client 
{

    public void non_Client_Socket()
    {
        SocketChannel sChannel=null;
        try
        {
            sChannel = SocketChannel.open();
            sChannel.connect(new InetSocketAddress("localhost", 80));
            while (!sChannel.finishConnect())
            {
                System.out.println("Channel is not connected yet");
                Thread.sleep(5000);
            }

            System.out.println("Channel is ready to use");

            /* ----------  going to send data to server ------------*/   
            System.out.println("please enter the text");
            BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
            while(true)
                {
                    System.out.println("Enter the text");
                    String HELLO_REQUEST =stdin.readLine().toString();
                    if(HELLO_REQUEST.equalsIgnoreCase("end"))
                    {
                        break;
                    }

                    System.out.println("Sending a request to HelloServer");    
                    ByteBuffer buffer = ByteBuffer.wrap(HELLO_REQUEST.getBytes());    
                    sChannel.write(buffer); 
                }  
        }
        catch(Exception E)
        {

        }

         finally
        {       
            if (sChannel != null)
            {            
                try 
                {             
                   sChannel.close();            
                }
                catch (Exception e)
                {           
                    e.printStackTrace();       
                }       
            } 

        }  } 
         /* ----------  the data is written in sChannel server will read from this channel  ------------   */




    public static void main(String [] args)throws Exception
    {
        new Client().non_Client_Socket();
    }}
ReadableByteChannel rbc = Channels.newChannel(sc.socket().getInputStream()); 

Your problem is here. 您的问题在这里。 You can't use a stream from a channel that's in non-blocking mode. 您不能使用处于非阻止模式的频道中的流。 The code is pointless anyway, as sc already is a ReadableByteChannel. 该代码毫无意义,因为sc已经是ReadableByteChannel。 Just delete this line and do the following I/O with sc instead of rbc . 只需删除此行,然后使用sc而不是rbc进行以下I / O。 But see below. 但请参见下文。

You still haven't fixed any of the issues I mentioned in your previous post . 您仍然没有解决我在上一篇文章中提到的任何问题。 Your connect technique is still wrong, and you are calling PrintRequest() which loops reading in non-blocking mode instead of registering the accepted channel for OP_READ. 您的连接技术仍然是错误的,并且您正在调用PrintRequest(),它以非阻塞模式循环读取,而不是为OP_READ注册可接受的通道。 The code continues to make no sense. 该代码仍然毫无意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 连接到Mpos设备会引发java.nio.channels.IllegalBlockingModeException - Connecting to Mpos Device throws java.nio.channels.IllegalBlockingModeException 写入客户端通道时出现异常java.nio.channels.ClosedChannelException - Exception java.nio.channels.ClosedChannelException when write to client channel 如何从客户端关闭套接字通道,以便服务器引发java.nio.channels.ClosedChannelException - How to close a socket channel from client side so that the server throws java.nio.channels.ClosedChannelException 从IO转移到NIO-网络,IllegalBlockingModeException - Moving from IO to NIO - Networking, IllegalBlockingModeException 限制Java NIO通道(文件或套接字)中可用的内容 - Limit the content available from a Java NIO Channel (File or Socket) 消耗来自风暴喷口的消息时,java.nio.channels.ClosedChannelException - java.nio.channels.ClosedChannelException while Consuming message from storm spout java.nio.channels。* - java.nio.channels.* java.nio.channels.ClosedChannelException-客户端关闭SSL - java.nio.channels.ClosedChannelException -Client shuts down SSL 例外:netty 3.10.6的套接字客户端的java.nio.channels.NotYetConnectedException - EXCEPTION: java.nio.channels.NotYetConnectedException for a socket client with netty 3.10.6 是否有任何支持java.nio.channels.SocketChannel的ssh客户端? - Is there any ssh client supporting java.nio.channels.SocketChannel?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM