【问题标题】:non blocking client server chat application in java using niojava中使用nio的非阻塞客户端服务器聊天应用程序
【发布时间】:2012-06-19 06:27:19
【问题描述】:

我使用 nio 频道构建了一个简单的聊天应用程序。我对网络和线程非常陌生。此应用程序用于与服务器通信(服务器/客户端聊天应用程序)。

我的问题是服务器不支持多个客户端。 我该如何解决这个问题? 我的代码有什么错误?

public class Clientcore extends Thread
{

    SelectionKey selkey=null;
    Selector sckt_manager=null;
    public void coreClient()
    {
       System.out.println("please enter the text");
       BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
       SocketChannel sc = null;
        try
        { sc = SocketChannel.open();
            sc.configureBlocking(false);       
            sc.connect(new InetSocketAddress(8888));  
            int i=0;
           while (!sc.finishConnect())
            {   
            } 
            for(int ii=0;ii>-22;ii++)
            {
                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());    
                sc.write(buffer); 
            }   
        } 
        catch (IOException e) 
        {          
            e.printStackTrace();    
        }
        finally
        {       
            if (sc != null)
            {            
                try 
                {             
                    sc.close();            
                }
                catch (Exception e)
                {           
                    e.printStackTrace();       
                }       
            } 
            }   }

     public void run()
     {
      try
      {
        coreClient();
      }
      catch(Exception ej)
      {
         ej.printStackTrace();
      }}}

public class ServerCore extends Thread
{

    SelectionKey selkey=null;
    Selector sckt_manager=null;
      public void run()
     {
        try
        {
            coreServer();
        }
        catch(Exception ej)
        {
            ej.printStackTrace();
        }
     }

    private void coreServer() 
    {
        try
        {
            ServerSocketChannel ssc = ServerSocketChannel.open();
              try
                 {   
                    ssc.socket().bind(new InetSocketAddress(8888));   

                     while (true)
                     { 

                         sckt_manager=SelectorProvider.provider().openSelector();
                         ssc.configureBlocking(false);   
                         SocketChannel sc = ssc.accept();
                         register_server(ssc,SelectionKey.OP_ACCEPT);
                        if (sc == null) 
                         {   
                        } 
                         else
                            { 

                                System.out.println("Received an incoming connection from " + sc.socket().getRemoteSocketAddress()); 
                                printRequest(sc); 
                                System.err.println("testing 1");
                                String HELLO_REPLY = "Sample Display";
                                ByteBuffer buffer = ByteBuffer.wrap(HELLO_REPLY.getBytes());
                                System.err.println("testing 2");
                                sc.write(buffer); 
                                System.err.println("testing 3");
                                sc.close();
                            }}}
              catch (IOException e)
              { 
                   e.printStackTrace(); 
              }
               finally
              { 
                   if (ssc != null) 
                   { 
                    try 
                    { 
                            ssc.close(); 
                    }
                    catch (IOException e) 
                    { 
                            e.printStackTrace(); 
                    }
                   }
               }
        }
        catch(Exception E)
        {
            System.out.println("Ex in servCORE   "+E);
        }    
    }


    private static void printRequest(SocketChannel sc) throws IOException
          {

                ReadableByteChannel rbc = Channels.newChannel(sc.socket().getInputStream()); 
                 WritableByteChannel wbc = Channels.newChannel(System.out); 
                 ByteBuffer b = ByteBuffer.allocate(1024); // read 1024 bytes  
                 while (rbc.read(b) != -1) 
                 {
                    b.flip();
                    while (b.hasRemaining())
                    { 
                         wbc.write(b);
                         System.out.println();
                    }
                    b.clear();
                 }
          }
     public void register_server(ServerSocketChannel ssc,int selectionkey_ops)throws Exception
      {
        ssc.register(sckt_manager,selectionkey_ops);
       }}

public class HelloClient
{

  public void coreClientChat() 
    {
        Clientcore t=new Clientcore();
        new Thread(t).start();
    }

    public static void main(String[] args)throws Exception
    {     
       HelloClient cl= new HelloClient();
       cl.coreClientChat();
    }}
public class HelloServer
    {

          public void coreServerChat()
          {
              ServerCore t=new ServerCore();
              new Thread(t).start();
          }

          public static void main(String[] args)
          {    
             HelloServer st= new HelloServer();
             st.coreServerChat();

          }}

【问题讨论】:

  • “服务器不支持多客户端”到底是什么意思。你试过什么吗?你有错误吗?请解释更多。
  • 你到底是从哪里得到这个可怕的代码的?为什么每次循环都创建一个新的选择器,然后不全部使用它?为什么每次循环时都需要将服务器通道置于非阻塞模式?

标签: java multithreading networking


【解决方案1】:

初学者的理想之地 Hello NIO Server

【讨论】:

  • 链接页面上的例子太琐碎了,它有一个问题:它使用了一个写循环。我想知道在哪里可以找到一个的例子。
  • 如果是使用NIO,这样你就可以根据自己的方便切换读写模式了。或者你可以试试“netty”,nio 框架。 NIO 有很多可用的示例。
  • @vadipp 我同意你的观点,这个例子很简单。它甚至不使用非阻塞模式,当然也没有表现出适当的多客户端处理。它没有回答你的问题。您是否考虑过 Oracle NIO 教程?那是你应该看的第一个地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
相关资源
最近更新 更多