سؤال

I have to create an application having a GUI. my application has to work as a server. When it starts, it has to accept all the incoming connection and write the output in a JTextArea. my problem is where I have to create the ServerSocket ss = new ServerSocket(port_number) and the method ss.accept in the way I can accept connections. I tried to create in the main constructor of my gui but being ServerSocket anI/O request the gui stucks.some idea to resolve the solution?

I create in the constructor of my GUI:

SwingUtilities.invokeLater(new Runnable(){public void run(){connection();}});

where connection() is the method where I create the serversocket and accepts call

هل كانت مفيدة؟

المحلول

You should create a separate thread to wait/handle the network connections.

When a new connection comes in read the data and pass them to the EDT to update the GUI.

This way the GUI will be responsive.

You should read about MVC Pattern threads. If you Google there is an abundance of articles to study

UPDATE:

Your code here is wrong.

SwingUtilities.invokeLater(new Runnable(){public void run(){connection();}});

You are handling the connection from the EDT thread.
You should use this to update the GUI and not to call the network I/O code.

نصائح أخرى

The IO logic must be in (at least one) separate background thread. Each time something must be printed to the text area from one of those background threads, they should do it using SwingUtilities.invokeLater(), to make sure that the Swing components are only accessed from the event dispatch thread.

That said, I don't think it's a very good idea to have a GUI for a server. Why don't you simply write in a log file, and use any text editor to see what the server received. Or write the GUI of the server as a client of this server?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top