当前位置: 首页 > 面试题库 >

使用nio在Java中不阻塞客户端服务器聊天应用程序

袁泓
2023-03-14
问题内容

我使用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();

          }}

问题答案:

初学者Hello NIO
Server的
理想之地



 类似资料:
  • 我想知道,如果可能的话,如何执行在 C 中创建/模拟 java 服务器套接字的任务?我是C的新手,但我相当精通Java。我的服务器(用java编写)需要从所有Java / C客户端接收数据(数据使用JSON Strings传输),但我不确定如何在C中与NIO服务器建立连接。 提前感谢任何帮助!

  • 主要内容:1 非阻塞服务器-GitHub仓库,2 无阻塞IO管道,3 非阻塞与阻塞IO管道,4 基本的无阻塞IO管道设计,5 读取部分消息,6 存储部分消息,7 编写部分消息,8 总结,9 服务器线程模型即使你了解了Java NIO非阻塞功能如何工作(Selector,Channel, Buffer等),设计一个无阻塞服务器仍然很难。与阻塞IO相比,非阻塞IO包含多个挑战。这份非阻塞服务器教程将讨论非阻塞服务器的主要挑战,并为它们描述一些潜在的解决方案。 本教程中描述的思想是围绕Java NIO

  • 我想在java上创建一个客户机/服务器应用程序,服务器的IP地址为192.168.1.100,在端口4500上等待客户机请求。 客户端从键盘上读取字符串,向服务器发送连接请求。一旦建立了连接,它就会将字符串发送到服务器。 这是我尝试的代码: 对于服务者: 对于客户端: 但这段代码有一个问题:

  • 我需要在netty中有一个客户机/服务器通信,用于我的项目目的之一。所以我刚开始用一个handsOn来改进,我正在学习netty,我是一个初学者。 我尝试了一个简单的客户端服务器与Netty聊天。 客户端和服务器正在初始化,我可以看到服务器能够获得用于建立连接的客户端管道,但是当客户端发送消息时,它没有进入ServerAdapterHandler的messageReceived部分。下面是我的源代

  • 我只是想知道是否可以使用SocketChannel类(带有ByteBuffer)来模拟Java中常规Socket类的阻塞特性。我做了两个测试项目,一个模拟客户端,另一个模拟服务器: 客户代码: 服务器代码: 正如我在评论中所说,运行服务器然后客户端(按该顺序)的结果是不可预测的,因为有时第二个数字可能保持为4或变为6,而更改分别为-1或4(整数字节)。 至于服务器端,我知道我可以让它等待第二个so