create a server application having gui - java

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?

Related

Swing Worker Usage in mixed threads

I have a GUI which consists of a toolbar with each button invoking different classes. The class I invoke consist of UI components which are displayed in the Internal frame of the main GUI. The Invoked class works as a separate thread and has to perform the following functions.
Trigger a command to the client, so that the client starts sending
the contents of a file.
Receive the file contents here,filter it and add it to a JTable.
Progress bar has to be displayed during the file contents transfer.
Display the UI after adding it to the table.
I am new to Swing worker, so can some one help me to get how it works with my situation and the advantages of using Swing Worker and Invoke later function. I followed the examples in the oracle site and few other sites but I am not able to see how this works for my classes.
SwingWorker has...
Progress change functionality built in, via the PropertyChange support
Has helper methods that allow you to synchronise updates to the UI via the publish and process methods, making the process significantly easier...
A self contained workflow concept which makes it (generally) easier to use than rolling your own. There are exceptions to the rule, but your outline doesn't fit those exceptions (IMHO) - this is both and advantage and disadvantage...
For example...
java swingworker thread to update main Gui
JProgressBar won't update
Populating jTable using database data (relates to updating a JTable from a SQL source, but shows how a SwingWorker might be used to update a JTable)
One of the (possible) drawbacks to SwingWorker is it will only allow (I believe) 10 workers to be executed simultanously

java gui and logic

it s 3 hours i m tring to understand a thing but no success...
the problem is:
i have a class Gui( a client) with a main for a cardgame. the Gui has a main that has in an invokelater a Runnable where the logic ( a separate class managing the gamesession) runs and some methods to manipulate the order of the cards.
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
PokerClientGui gui = new PokerClientGui();
gui.setVisible(true);
PokerClient pokerClient = new PokerClient(gui);
pokerClient.gameSession();
}
});
}
The logic is created in the main of the Gui passing the Gui itself to the logic.
As far as i am proceding in the program there are no problems since all the objects/strings sent from the server to the client logic are received and for example the Hand is passed to the gui and displayed correctly.
The problem comes now: i want to pass from the gui to the logic, the manipulated hand to send it to the sever via method of the logic class.
Since this function is called by the event mouse on the Gui (and not in the main of the Gui) i have no handle to the logic object so i can t use its sending objects method.
I tried changing to static the method of the logic that sends and i made statics also the member involved in sending things on the socket.....
it doesn t send anything ..... it s not a problem of something wrong and i try to catch the exceptions (and nothing comes from them)
where m i wrong? what i am missing ? how should i bind the gui and the logic?
Perhaps you could create an event queue in your Runnable() class, and pass it to both your gui and your client constructors.
The client would add events for the GUI to display, and the GUI would add events for the client to process. It might be easier with two queues, one for each direction, rather than re-using a single channel for both directions.
Then your GUI and your client would add the event queue from this object into the list of things to 'check' when waiting in their event loops. When an event comes from the other object, it wakes the current object to do processing, same as events from the server or the user.
In place of creating the object of PokerClientGui in main class u better create its object directly in the PokerClient object and access its object gameSession() .

Is the jtextarea.settext() method buffered?

i'm not a java developer, but i need to write a small applet to upload file via ftp
(actually, i'm a web developer). Everything works fine, except for the way that feedback messages are displayed. Let me explain with an example:
if i wrote sometingh like that, inside a method (controlled by a click event)
//....
myJpanel.setText("Connecting to remote server");
//actually, it's surrounded by try-catch statement
myFtpObject.connect(); //this is taken from a third part package
myJpanel.setText("Connected")
When I try to run this code the connection is set (after that connection I upload files with no problem), but inside the Jpanel myJpanel I immeditaly read "connected" (altought it takes several seconds to connect) and I never see the "Connecting to remote server" string.
It sounds to me like the Jpanel setText method is buffered in some way.
How can I display messages in real time?
(I've tried to do System.out.println for testing and it worked great!)
Thanks
if i wrote sometingh like that inside a method (controlled by a click event)
Code executed in an event listener executes on the EDT. The problem is that the long running task is blocking the Swing EDT. So the GUI never gets a chance to repaint itself.
Read the section from the Swing tutorial on Concurrency for more information and for a solution. The basic solution is to create a separate thread for the long running task.
This is also why System.out.println(..) works, because it executes on a different Thread.

IO thread alert GUI thread if error occures

I have a client/server question that i am trying to figure out the best solution for.
If a client ever gets disconnected from the server, for any reason, i would like a way for the input output thread to alert the gui thread that something went wrong, and thus have the gui thread print an error and gracefully handle it (probably drop back out to the login gui). After the initial gui thread is created, the client could change to any number of guis, depending on what he is doing, so I am thinking i need a way to dynamically see what gui is currently being run.
The way that i was thinking of doing this so far:
1) Create an object that creates and shows every gui. So instead of calling invokeLater...SomeGui.CreateAndShoGui()... we would have this object be responsible for doing that, ie GuiObject.showSomeGui();
2) Have each gui implement an interface, which will insure there is a method that, when called, will gracefully shutdown this gui when we have lost connection to the server.
3) Have a thread that monitors the IO thread and the gui object. If something goes wrong on the IO thread, the IO thread will close down and notify the monitoring thread that we have lost connection the server. The monitoring thread could then alert any open guis (from the gui object) that we have lost connection and that it needs to shut down.
I have just started thinking about this, and so far this is the best solution i have come up with. Does this seem like a reasonable solution that wont add too much complexity to the code? Or can anyone recommend a solution that would be simpler for people reading the code to understand?
Thanks
EDIT:
The other option i am toying with is having an object on the IO thread, that also gets passed to each new gui as it is opened. This object will give the currently opened guis reference back to the io thread, so that the io thread can alert it if something goes wrong. I am leaning against this solution though, because it seems like it would be easier to read if you had one object that was dedicated to get this working (like the above solution), instead of passing some obscure object to each gui.
Let me just go through each of your ideas:
1) Bad idea - you are tying your whole application together through a single object. This makes maintainability difficult and is the antithesis of modularity.
2) This is the way to go IMHO. Since it seems that each gui has unique logic in a failure scenario then it stands to reason that the object that best understands what to do would be the gui object itself.
Another version of this idea would be to create an adapter for each gui to put this failure logic into. The advantage would be you have one less dependency between your application framework and your gui. The disadvantage is that this is an extra layer of complexity. If your gui is already pretty coupled to your application then I would choose the interface method. If you want to reuse your guis in another application then the adapter way could help facilitate that.
3) This complements #2 nicely. So let me get this straight - you would have 3 threads: the IO thread, the monitor thread, and the UI thread. I don't know if you need the monitor thread. From what you were saying the IO thread would be able to detect a connection problem by itself (probably because some form of IOException was caught). When a connection problem is discovered the IO thread is not busy since it is just going to shut itself down soon so it might as well just have the responsibility of notifying the guis that there was a problem. The guis should have their interface method called on the UI thread anyways so the IO thread is just calling a bunch of invokeLater() calls (or asyncExec() calls for SWT) and then the IO thread can just shut itself down.
4) (Your Edit) You are basically describing the Visitor pattern. I do not think this is a good solution because the call is from the IO thread to the gui and not the other way around. I am not sure how passing a visitor object around will help in this case.
One final thought. If you make your interface generic (not gui specific) then you can apply this pattern to other resources. For instance you may want to flush your user credentials when you lose connection (since you talked about going to the login screen again). That isn't really gui logic and should not be done from a gui class.
Edit: I would use an event model. Let's say you create a interface like this:
public interface ConnectionFailureListener {
void handleConnectionFailure(); // Add an event object if you need it
}
You could then have registration methods in some object (maybe the Runnable for the IO thread or somewhere else that is convenient for you). These methods would be pretty standard:
public void addConnectionFailureListener(ConnectionFailureListener l) {}
public void removeConnectionFailureListener(ConnectionFailureListener l) {}
When you show a gui on the screen you would add it to your registration object and when you close the gui you would remove it from the registration object. You can add other types of objects as needed - for example when you log in you can add a listener for your credential system and remove it again when log out is processed.
This way when you have a failure condition you simply loop through the currently registered listeners and the listener does its thing.

Java Communication Between Classes and JFrame JDialog

i have written a standalone connect 4 game.
next i would like to be able to play it over network and also have a chat function.
connect 4 GUI (JFrame) holds -> connect 4 game model
i would like to implement connect 4 network GUI(JDialog) (here the user can choose to act as a server or client) that holds Network API. (server only serving a single connection)
and finally a Chat GUI (JDialog) to exchange messages.
my question is how do i implement inter class/GUI communication? when a network message is received it ought to be delivered to the right receiver (game / chat) also messages sent from chat / game transmitted to remote machine.
i have looked into inner classes but was told it is a bad idea to implement so much with in single class and i did not like this idea a lot either.
i have written another game battleships in C# and it uses delegates to accomplish this task but sadly im informed that delegates are not available in Java.
im a beginner and at the moment exploring options so im open to your guidance.
thank you.
There are two issues here.
First, you must remember that all GUI operation must be issued from the Swing's Event Dispatching Thread (EDT). So, if another thread (such as the thread listening to network messages) want to update the GUI it must use SwingUtilities.invokeLater as follows:
// Network thread
final Message msg = getMessage();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// This code will be executed on the EDT
// it can access the msg variable because it is final
}
});
The second point is that of coordinating the GUI objects and networking objects. I think the best approach is to create two Mediator classes that will receive notifications from the networking object and "translate" them into appropriate action on the GUI object (and vice versa). These mediators will also make sure that GUI events are dispatched on the EDT, as explained above.

Categories