Mike
Mike

Reputation: 23

Java TCP Server

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

Answers (5)

Duy Do
Duy Do

Reputation: 96

Simplest thing is building your server in separate thread.

Upvotes: 0

Dan LaRocque
Dan LaRocque

Reputation: 5183

There are two basic approaches to socket programming in Java:

  1. Use one thread per Socket
  2. Use Non-Blocking IO in one or a small number of threads

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

Yann Ramin
Yann Ramin

Reputation: 33167

Threads.

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

Luis Miguel Serrano
Luis Miguel Serrano

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

Steven Schlansker
Steven Schlansker

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

Related Questions