【问题标题】:Console based application to GUI based application in JavaJava中基于控制台的应用程序到基于GUI的应用程序
【发布时间】:2012-09-29 19:49:46
【问题描述】:

我已经创建(通过从互联网收集一些代码 sn-ps)基于控制台的 LAN 聊天应用程序。现在我想

使用 Netbeans IDE 7.1 制作 GUI。 它是一个多线程应用程序。 在我基于控制台的应用程序中,每当我想显示输出时,我都会这样做

System.out.println(msg) . 

现在我想在 JFrame 表单中完成,

jTextField1.setText(msg). 

我是否需要创建一个新的主类并在 JFrameForm 中创建一个实例并通过调用使其可见

new NewJFrame().setVisible(true); 

或者我应该在 JFrame 类本身中完成所有编码。我在下面显示我的实际和工作代码(在控制台中)

import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class MultiThreadChatClient implements Runnable {

  // The client socket
  private static Socket clientSocket = null;
  // The output stream
  private static PrintStream os = null;
  // The input stream
  private static DataInputStream is = null;

  private static BufferedReader inputLine = null;
  private static boolean closed = false;

  public static void main(String[] args) {

    // The default port.
    int portNumber = 2222;
    // The default host.
    String host = "127.0.0.1";

    if (args.length < 2) {
      System.out
          .println("Usage: java MultiThreadChatClient <host> <portNumber>\n"
              + "Now using host=" + host + ", portNumber=" + portNumber);
    } else {
      host = args[0];
      portNumber = Integer.valueOf(args[1]).intValue();
    }

    /*
     * Open a socket on a given host and port. Open input and output streams.
     */
    try {
      clientSocket = new Socket(host, portNumber);
      inputLine = new BufferedReader(new InputStreamReader(System.in));
      os = new PrintStream(clientSocket.getOutputStream());
      is = new DataInputStream(clientSocket.getInputStream());
    } catch (UnknownHostException e) {
      System.err.println("Don't know about host " + host);
    } catch (IOException e) {
      System.err.println("Couldn't get I/O for the connection to the host "
          + host);
    }

    /*
     * If everything has been initialized then we want to write some data to the
     * socket we have opened a connection to on the port portNumber.
     */
    if (clientSocket != null && os != null && is != null) {
      try {

        /* Create a thread to read from the server. */
        new Thread(new MultiThreadChatClient()).start();
        while (!closed) {
          os.println(inputLine.readLine().trim());
        }
        /*
         * Close the output stream, close the input stream, close the socket.
         */
        os.close();
        is.close();
        clientSocket.close();
      } catch (IOException e) {
        System.err.println("IOException:  " + e);
      }
    }
  }

  /*
   * Create a thread to read from the server. (non-Javadoc)
   * 
   * @see java.lang.Runnable#run()
   */
  public void run() {
    /*
     * Keep on reading from the socket till we receive "Bye" from the
     * server. Once we received that then we want to break.
     */
    String responseLine;
    try {
      while ((responseLine = is.readLine()) != null) {
        System.out.println(responseLine);
        if (responseLine.indexOf("*** Bye") != -1)
          break;
      }
      closed = true;
    } catch (IOException e) {
      System.err.println("IOException:  " + e);
    }
  }
}

//MultiThreadServer.java


import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;

/*
 * A chat server that delivers public and private messages.
 */
public class MultiThreadChatServer {

  // The server socket.
  private static ServerSocket serverSocket = null;
  // The client socket.
  private static Socket clientSocket = null;

  // This chat server can accept up to maxClientsCount clients' connections.
  private static final int maxClientsCount = 10;
  private static final clientThread[] threads = new clientThread[maxClientsCount];

  public static void main(String args[]) {

    // The default port number.
    int portNumber = 2222;
    if (args.length < 1) {
      System.out
          .println("Usage: java MultiThreadChatServer <portNumber>\n"
              + "Now using port number=" + portNumber);
    } else {
      portNumber = Integer.valueOf(args[0]).intValue();
    }

    /*
     * Open a server socket on the portNumber (default 2222). Note that we can
     * not choose a port less than 1023 if we are not privileged users (root).
     */
    try {
      serverSocket = new ServerSocket(portNumber);
    } catch (IOException e) {
      System.out.println(e);
    }

    /*
     * Create a client socket for each connection and pass it to a new client
     * thread.
     */
    while (true) {
      try {
        clientSocket = serverSocket.accept();
        int i = 0;
        for (i = 0; i < maxClientsCount; i++) {
          if (threads[i] == null) {
            (threads[i] = new clientThread(clientSocket, threads)).start();
            break;
          }
        }
        if (i == maxClientsCount) {
          PrintStream os = new PrintStream(clientSocket.getOutputStream());
          os.println("Server too busy. Try later.");
          os.close();
          clientSocket.close();
        }
      } catch (IOException e) {
        System.out.println(e);
      }
    }
  }
}

//ChatClient.java

/*
 * The chat client thread. This client thread opens the input and the output
 * streams for a particular client, ask the client's name, informs all the
 * clients connected to the server about the fact that a new client has joined
 * the chat room, and as long as it receive data, echos that data back to all
 * other clients. When a client leaves the chat room this thread informs also
 * all the clients about that and terminates.
 */
class clientThread extends Thread {

  private DataInputStream is = null;
  private PrintStream os = null;
  private Socket clientSocket = null;
  private final clientThread[] threads;
  private int maxClientsCount;

  public clientThread(Socket clientSocket, clientThread[] threads) {
    this.clientSocket = clientSocket;
    this.threads = threads;
    maxClientsCount = threads.length;
  }

  public void run() {
    int maxClientsCount = this.maxClientsCount;
    clientThread[] threads = this.threads;

    try {
      /*
       * Create input and output streams for this client.
       */
      is = new DataInputStream(clientSocket.getInputStream());
      os = new PrintStream(clientSocket.getOutputStream());
      os.println("Enter your name.");
      String name = is.readLine().trim();
      os.println("Hello " + name
          + " to our chat room.\nTo leave enter /quit in a new line");
      for (int i = 0; i < maxClientsCount; i++) {
        if (threads[i] != null && threads[i] != this) {
          threads[i].os.println("*** A new user " + name
              + " entered the chat room !!! ***");
        }
      }
      while (true) {
        String line = is.readLine();
        if (line.startsWith("/quit")) {
          break;
        }
        for (int i = 0; i < maxClientsCount; i++) {
          if (threads[i] != null) {
            threads[i].os.println("<" + name + "&gr; " + line);
          }
        }
      }
      for (int i = 0; i < maxClientsCount; i++) {
        if (threads[i] != null && threads[i] != this) {
          threads[i].os.println("*** The user " + name
              + " is leaving the chat room !!! ***");
        }
      }
      os.println("*** Bye " + name + " ***");

      /*
       * Clean up. Set the current thread variable to null so that a new client
       * could be accepted by the server.
       */
      for (int i = 0; i < maxClientsCount; i++) {
        if (threads[i] == this) {
          threads[i] = null;
        }
      }

      /*
       * Close the output stream, close the input stream, close the socket.
       */
      is.close();
      os.close();
      clientSocket.close();
    } catch (IOException e) {
    }
  }

【问题讨论】:

    标签: java swing sockets concurrency event-dispatch-thread


    【解决方案1】:

    虽然严格来说不是原始问题的一部分,但控制台应用程序和 GUI 应用程序之间存在许多非常重要的区别。

    首先,线程模型是不同的,并且非常重要,您需要花时间了解它是什么、在哪里以及如何使用它。

    首先,永远不要在Event Dispatching Thread(aka EDT)(主 UI 线程)中做任何会阻塞它的事情,例如 IO 操作...如果可能,请在里面的后台执行这些操作另一个线程或worker

    永远不要从除 EDT 之外的任何线程更新 UI 组件。 SwingWorker 可以在某些情况下提供帮助,当它不能提供帮助时,您需要依赖 SwingUtilities.invokeLater/invokeAndWait

    【讨论】:

      【解决方案2】:

      我假设 Netbeans IDE 开发应用程序,而不是使用 Netbeans 平台。有一篇关于构建聊天客户端的 DZone 博客文章。我认为您需要根据您的问题阅读摇摆。这篇博文使用 AWT,但它对您来说是一个好的开始。

      http://www.javaworld.com/jw-01-1997/jw-01-chat.html

      【讨论】:

        【解决方案3】:

        Java 是一种面向对象的语言,所以我认为您应该创建一个类似 ChatFrame 的类,并且这个 ChatFrame 类应该扩展 JFrame 类。 (或者可以有一个 JFrame 实例,它用于“showChatFrame”之类的方法中,在这一点上感谢 Hovercraft Full Of Eels!)

        所以你可以在这个 ChatFrame 类中编写每个 gui 代码,并在另一个类中编写服务器通信代码。

        使用强大的模块是一种很好的编码风格。您的软件应该是几个模块,它们通过接口相互通信(并非每次都是真正的 Java 接口)。

        你的 Main 类应该只包含 main 方法,例如创建一个 ServerCommunication 对象,该对象进行通信并使用 ChatFrame 类向用户显示消息。

        【讨论】:

        • 我同意他应该将他的关注点分开——有一个 GUI 或一系列 GUI“视图”类,并有单独的聊天机制类,但有一个小问题:我不同意任何 GUI 类 extend JFrame,因为通常不需要这样做,因为我们很少会通过覆盖其中一个方法来改变 JFrame 的基本行为。
        猜你喜欢
        • 2011-05-12
        • 1970-01-01
        • 1970-01-01
        • 2010-10-15
        • 1970-01-01
        • 2020-08-08
        • 2014-01-01
        • 1970-01-01
        • 2012-06-11
        相关资源
        最近更新 更多