Skip to content

Java TCP Client/Server

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



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.

User contributions licensed under: CC BY-SA
7 People found this is helpful