Reputation: 23
I'm building a GUI application which needs to have a TCP Server running. The GUI is built in Swing. The trouble I'm having is running the server. I want to have one desktop application people can install, that will in turn start the server for me. The server is blocking while it runs ie:
while (true) {
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
....
I tried to call the server class, but then it blocks the GUI. What do you think is the best way to separate the Server from the GUI, while easily being able to package both together? Thanks for any help!
Upvotes: 2
Views: 1605
Reputation: 5183
There are two basic approaches to socket programming in Java:
You probably want the first one. If you don't know which one you want, then you almost certainly want the first one. This is subjective, but I think most people would agree #1 is easier to get correct.
Here's an answer that discusses the difference.
Assuming you decide to go with threads, use a thread pool! It's easy and tidy.
I think you're past this stage, but if you want some basic "101" type material, the old Sun tutorial on Sockets and Threads is dusty but useful.
Upvotes: 5
Reputation: 33167
Note that once you introduce multi-threaded programming, there are a lot of gotchas. One important one is that access to any Swing or GUI element must be done in the Swing Event Thread. You can use SwingWorkers to make that task easier.
You can also use Java NIO.
Upvotes: 2
Reputation: 5099
Well, from your description, perhaps the problem is that you need to put the GUI and the server part (with that while(true) ), into separate Threads, so that you can handle user generated events.
Upvotes: 0
Reputation: 38526
The easiest solution is generally to run your ServerSocket in a different thread. You may also try things like asynchronous IO, but it's a real pain.
Upvotes: 1