簡體   English   中英

套接字服務器客戶端線程,Java

[英]Socket Server Client Thread, Java

我在這個問題之前問過...

我想測試網絡中的TCP套接字行為,因為我需要測試Java應用程序...

我使用線程創建了服務器客戶端模型示例。

這里的ConsumerServer

  public class ConsumerServer extends Thread {
    private ServerSocket SrvrScktConsumer;
    Socket clientSocket = null;
    private boolean isConsumerRunning = false;

    public ConsumerServer(int ConsPort) {
      try {
        SrvrScktConsumer = new ServerSocket(ConsPort);
        System.out.println(NL + "ConsumerServer Listening on port number: " + ConsPort);
      } catch (IOException e) { }
    }

    @Override public void run() {
      try {
        clientSocket = SrvrScktConsumer.accept();
        InputStream input;
        byte[] innerBytes = new byte[1024];
        try {
          input  = clientSocket.getInputStream();
          Integer iRemotePort = clientSocket.getPort();
          String sRemoteHost = clientSocket.getInetAddress().getHostAddress();
          System.out.println("ConsumerServer: Remote Connection\n\tPort:" + iRemotePort+ " Host:" + sRemoteHost);
          isConsumerRunning = true;
          while (isConsumerRunning) {
            try {
              byte[] incomingBytes = Arrays.copyOf(innerBytes, input.read(innerBytes));
              jtaMessages.append(NL + "Consumer GET " + new String(incomingBytes));
              jtfLastReceived.setText(new String(incomingBytes));
            } catch (IOException | NegativeArraySizeException | IndexOutOfBoundsException e) {
              isConsumerRunning = false;
            }
          }
          System.out.println(NL + "ConsumerClient closing from Host " + sRemoteHost + " Port " + iRemotePort);
          try {  if (input != null) input.close(); } catch (IOException e) { }
        } catch (IOException e) {
          System.out.println(NL + "Error Creating ConsumerClient\n\t:" + e.toString());
        }
      } catch (IOException | NullPointerException e) {
          System.out.println(NL + "ConsumerServer Stopped: " + e.toString()) ;
      }
      System.out.println(NL + "Exiting ConsumerServer...");
    }

    public void stopServer() {
      try {
        SrvrScktConsumer.close();
      } catch (IOException | NullPointerException e) { }
      try {
        clientSocket.close();
      } catch (IOException | NullPointerException e) { }
      isConsumerRunning = false;
    }
  };

這里的ProducerClient

  public class ProducerClient extends Thread {
    private Socket clientSocket = null;
    private OutputStream output = null;
    private boolean isProducerRunning = false;

    public ProducerClient(String ConsHost , int ConsPort) {
      try {
        clientSocket = new Socket(ConsHost, ConsPort);
        output = clientSocket.getOutputStream();
        System.out.println(NL + "ProducerClient Connected to port number: " + ConsPort);
      }
      catch (IOException e) { }
    }

    @Override public void run() {
      if (!(clientSocket == null)) {
        Integer iLocalPort = clientSocket.getLocalPort();
        String sLocalHost = clientSocket.getLocalAddress().getHostAddress();
        System.out.println("ConsumerServer: Local Connection\n\tPort:" + iLocalPort+ " Host:" + sLocalHost);
        int ctrlPrintOut = 0, ctrlPrintIn = 0;
        isProducerRunning = true;
        while (isProducerRunning) {
          try {
            if (bProducerReady) {
              bProducerReady = false;
              output.write(jtfSendMessage.getText().getBytes());
              jtaMessages.append(NL + "Producer PUT " + jtfSendMessage.getText());
              jtfSendMessage.setText("");
            }
//            // Ini Code Block to delete
//            else {
//              try {
//                Thread.sleep(1);
//              } catch (InterruptedException ex) { }
//              if (ctrlPrintOut == 1000000 /*Integer.MAX_VALUE*/) {
//                if (ctrlPrintIn == 2) {
//                  System.out.println("ProducerClient Waiting!");
//                  ctrlPrintIn = 0;
//                }
//                ctrlPrintIn++; ctrlPrintOut = 0;
//              }
//              ctrlPrintOut++;
//            }
//            // End Code Block to delete
          } catch (IOException e) {
            System.out.println("ProducerClient: " + e.toString());
            isProducerRunning = false;
          }
        }
        try { output.close(); } catch (IOException e) { }
        try { clientSocket.close(); } catch (IOException e) { }
        System.out.println(NL + "Exiting ProducerClient...");
      }
    }

    public void stopClient() {
      try {
        clientSocket.close();
      } catch (IOException | NullPointerException e) { }
      isProducerRunning = false;
    }
  };

我想刪除指示的阻止代碼,但是當我刪除時..我的測試無法正常工作。

這里的班級使用之前的班級

public class ClientServerShort extends JFrame {

  private JButton jbSendMessage = new JButton("Send Message");
  private JLabel jlLastReceived = new JLabel("Last Received");
  private JTextArea jtaMessages = new JTextArea(5,20);
  private JScrollPane jspMessages = new JScrollPane(jtaMessages);
  private JToggleButton jtbConsumer = new JToggleButton("Launch Consumer Server");
  private JToggleButton jtbProducer = new JToggleButton("Launch Producer Client");
  private JTextField jtfLastReceived = new JTextField();
  private JTextField jtfSendMessage = new JTextField();

  static boolean bProducerReady = false;
  static final String NL = System.getProperty("line.separator");
  ConsumerServer thrdConsumerServer = null;
  ProducerClient thrdProducerClient = null;

  public ClientServerShort() {
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    jbSendMessage.addActionListener((ActionEvent evt) -> {
      if (!jtfSendMessage.getText().isEmpty()) {
        bProducerReady = true;
      }
    });

    jlLastReceived.setBorder(BorderFactory.createEtchedBorder());
    jlLastReceived.setHorizontalAlignment(SwingConstants.CENTER);

    jtbConsumer.addActionListener((ActionEvent evt) -> {
      if (jtbConsumer.isSelected()) {
        if (thrdConsumerServer == null) {
          thrdConsumerServer = new ConsumerServer(1027);
          thrdConsumerServer.start();
        }
      } else {
        if (thrdConsumerServer != null) {
          thrdConsumerServer.stopServer();
          thrdConsumerServer = null;
        }
      }
    });
    jtbProducer.addActionListener((ActionEvent evt) -> {
      if (jtbProducer.isSelected()) {
        if (thrdProducerClient == null) {
          thrdProducerClient = new ProducerClient("192.168.0.49", 1027);
          thrdProducerClient.start();
        }
      } else {
        if (thrdProducerClient != null) {
          thrdProducerClient.stopClient();
          thrdProducerClient = null;
        }
      }
    });

    jtfLastReceived.setEditable(false);

    JPanel jpMessagesUp = new JPanel();
    jpMessagesUp.setLayout(new GridLayout(2, 2, 6, 6));
    jpMessagesUp.add(jbSendMessage);
    jpMessagesUp.add(jtfSendMessage);
    jpMessagesUp.add(jlLastReceived);
    jpMessagesUp.add(jtfLastReceived);

    getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
    add(jtbProducer);
    add(jtbConsumer);
    add(jpMessagesUp);
    add(jspMessages);
    pack();
  }

  public static void main(String args[]) {
    EventQueue.invokeLater(() -> {
      new ClientServerShort().setVisible(true);
    });
  }

}

題:

是什么原因,為什么我刪除了指示代碼段代碼(在ProducerClient中),但我的Single App無法正常工作?

原因正好是我在另一個問題中告訴您的內容。 bProducerReady必須是volatile ,因為您正在從不同的線程讀取和寫入它。 您奇怪的延遲代碼只是通過時間來完成相同的內存刷新。

注意:它不必是static

為什么您重新發布這個已回答的問題仍然是個謎。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM