1

I have a problem which I do not know how to proceed further in Java TCP socket issue. So far as what we can get from the Internet, it's not hard to get quite a number of working solution for TCP server & client communication in Java. However, most of the example will have their server listen to a port, and then loop until they get a client which connects to the server, then the code will perform server.accept() and move further. For example:

 public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(PORT);
    System.out.println("Started: " + s);
    try {
      // Blocks until a connection occurs:
      Socket socket = s.accept();
      try {
        System.out.println("Connection accepted: "+ socket);

It will work perfectly if there's a client connecting to the server. And, my problem is that I need to continue some other procedures even though there's no client connecting to the server. In fact, I will need to launch another JFrame to continue the procedures even if there is no client connecting to the same port and ip. However, I have been struggling but as long as there is not client connecting to the server, my Java program will hang there with white popped up JFrame.

I would need to know how to overcome this as I am not quite sure whether there's a mistake in my understanding. Please assist and advice. Thank you!

Best Regards, Yi Ying

1 Answer 1

4

Sounds like you need to do work in one thread whilst waiting for network connections on another. Check out the threading tutorial. Note that since you're using Swing, you have to be careful wrt. which thread will modify your JFrame etc. and you should be aware of the SwingWorker utility.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 What Brian said. It's a common pattern to have your acceptor in one thread and have it spawn further worker threads when required to service the incoming connection. If you need speed, consider reducing the overhead of thread creation using pools.
Thank you all, I have sorted all things out by following Brian and John's advice. I have written the codes to create a new thread to listen while the the original procedures can continue to run. Thanks all!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.