Search code examples
javamultithreadingswingframeserversocket

JAVA SocketServer with frame


I'm trying to make Java socket Server, which has frame, where messages are displayed.

But when I run the server from frame constructor, the frame don't become visible.

There is part of my code:

Calling the frame:

    public static void main(String[] args) {

    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                new ServerForm().setVisible(true);
            } catch (IOException ex) {
                Logger.getLogger(Ship_Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

Creating the server:

    public ServerForm() throws IOException {
    initComponents();

    hipServer Server = new hipServer();

}

The server constructor:

 public ShipServer() throws IOException {
    ServerSocket listener = new ServerSocket(8901);
    System.out.println("Server is Running");
    try {
        while (true) {

          ...
         }
    } finally {
        listener.close();
    }
}

Can you suggest something, to run server, and live active frame?


Solution

  • Avoid having process intensive code in the EDT such as infinite while loops.

    Have a look at using a SwingWorker. It won't block the EDT while waiting for network connections. The ServerSocket functionality can be managed in doInBackground.