开发者

Java server client thread issue

Hello I have a very simple client-server program that uses sockets simulating a simple atm. In the client part of the program i have a gui class and another thread to communicate with the server so the gui and 开发者_如何学Gothe logic are separated and also the gui is not freezing while waiting the thread to communicate with the server.

I create one thread since the clientsocket is created upon connection and lives through the entire session.And the problem is that i have the thread looping in an endless loop and asking the gui if the user pressed any key so it can take care of the actions.

Any suggestions of best practises on this matter? I don't want to use RMI since i 'am developing for educational reasons.

Cheers


You could use a BlockingQueue. The GUI and the client thread would have access to the same queue object. In response to user action, the GUI could put() command objects onto the queue. The client thread will still have a while loop, BUT will use take() to pull command objects off of the queue. take() will block using proper thread synchronization primitives so you won't have a busy loop. The server response after a client command would likely involve updating some local state and/or updating the gui and I wouldn't be surprised if SwingWorker got involved.

There are many ways to solve this, but that is the first one that jumped into my head.


You should use more threads: A main thread for the UI, one thread that communicates with the server (TC) and one thread which contains the "business logic" (TBL). The TC and TBL threads should use BlockingQueue to wait for commands (see the command pattern).

When a button in the UI is clicked, a command is pushed in the queue of TC or TBL. They wait for these commands, execute them and either create more commands or update the UI (using SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater() as appropriate).

This allows you to untangle all threads. You can even test each of them individually by creating commands in your tests and pushing them into the correct queues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜