Need help improving a java client side port listener

前端 未结 2 1768
忘了有多久
忘了有多久 2021-01-23 03:06

I have a small bit of code that runs in an applet that contains SWING controls and is used to write information to a socket on a certain port and then listens for a response.

相关标签:
2条回答
  • 2021-01-23 03:22

    All the network I/O should be in a separate thread.

    BTW readLine() returns null when the server closes the connection, not when it has finished sending data for the moment.

    0 讨论(0)
  • 2021-01-23 03:23

    There lots of different means of getting the IO performed on a different thread, but in this case you probably want to use SwingWorker.

    Your code would look something like:

    private final Executor executor = Executors.newSingleThreadExecutor();
    
    public void writePacket(final String packet) 
    {
      // schedules execution on the single thread of the executor (so only one background operation can happen at once)
      //
      executor.execute(new SwingWorker<String, Void>()
          {
    
            @Override
            protected String doInBackground() throws Exception
            {
              // called on a background thread
    
    
              /* This method writes the packet to the port - established earlier */
              System.out.println("writing out this packet->"+packet+"<-");
              System.out.println(packet);
              String thePacket = readPacket();  //where the port listener is invoked.  
              return thePacket;            
            }
    
            @Override
            protected void done()
            {
              // called on the Swing event dispatch thread
    
    
              try
              {
                final String thePacket = get();
    
                // update GUI with 'thePacket'
              }
              catch (final InterruptedException e)
              {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
              catch (final ExecutionException e)
              {
                // TODO Auto-generated catch block
                e.printStackTrace();
              } 
            }
          });
    }
    
    private String readPacket() 
    {
      String thePacket ="";
      String fromServer="";
      //Below is the loop that freezes everything.   
      try 
      {
        while ((fromServer = in.readLine()) != null) 
        { 
          if (thePacket.equals("")) 
            thePacket = fromServer;
          else 
            thePacket = thePacket+newLine+fromServer;
        }
        return thePacket;  //when this happens, all listening should stop.   
      } 
      catch (IOException e) 
      {
        e.printStackTrace();
        return null;
      }
    }
    
    0 讨论(0)
提交回复
热议问题