1

So I have a server-client program which makes a screen capture and shows it on your screen. I want to verify in the main part if the port I want to connect to is in use or not and to print some relevant messages..

Server:

package test;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.SQLException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Server extends Thread
{
       private ServerSocket serverSocket;
       Socket server;

       public Server(int port) throws IOException, SQLException, ClassNotFoundException, Exception
       {
          serverSocket = new ServerSocket(port);
          serverSocket.setSoTimeout(180000);
       }

       public void run()
       {
           while(true)
          { 
               try
               {
                  server = serverSocket.accept();
                  BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));
                  JFrame frame = new JFrame();
                  frame.getContentPane().add(new JLabel(new ImageIcon(img)));
                  frame.pack();
                  frame.setVisible(true);                  
              }
             catch(SocketTimeoutException st)
             {
                   System.out.println("Socket timed out!");
                  break;
             }
             catch(IOException e)
             {
                  e.printStackTrace();
                  break;
             }
             catch(Exception ex)
            {
                  System.out.println(ex);
            }
          }
       }

//       private static boolean isLocalPortInUse(int port) {
//          try {
//              // ServerSocket try to open a LOCAL port
//              new ServerSocket(port).close();
//              // local port can be opened, it's available
//              return false;
//          } catch(IOException e) {
//              // local port cannot be opened, it's in use
//              return true;
//          }
//      }

       public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception
       {
              int port = 9000;
              Thread t = new Server(port);

              t.start();

       }
}

Client:

package test;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.Socket;

import javax.imageio.ImageIO;

public class Client
{   
    static BufferedImage img;
    byte[] bytes;

    public static void main(String [] args)
    {
        String serverName = "localhost";
        int port = 10001;
        try
        {
            Socket client = new Socket(serverName, port);
            Robot bot;
            bot = new Robot();//clasa Robot ajuta la creare capturii de ecran
            img = bot.createScreenCapture(new Rectangle(0, 0, 500, 500));//scalarea imaginii; schimba dimensiunea screen shotului
            ImageIO.write(img,"JPG",client.getOutputStream());
            System.out.println("The image is on the screen!Yey!");
            client.close();
        } catch(IOException | AWTException e) {
            e.printStackTrace();
        }
    }
}

1 Answers1

0

If the client and server are on the same box, then you can use the strategy of binding to the existing port and checking for a specific exception.

public static void main(String...args) throws IOException {
  int port = 31999; // for demonstration purposes only.

  boolean serverRunning = isServerRunning(port);
  System.out.printf("Server running: %s\n", serverRunning);

  new ServerSocket(port); // start the server

  serverRunning = isServerRunning(port);
  System.out.printf("Server running: %s\n", serverRunning);
}

private static boolean isServerRunning(int port) throws IOException {
  try(ServerSocket clientApp = new ServerSocket(port)) {
    return false;
  } catch (java.net.BindException e) {
    return true;
  }
}

If the server is on another box, which is most likely the case, then you can follow a similar strategy, instead looking for ConnectException

public static void main(String...args) throws IOException {
  int port = 31999; // for demonstration purposes only.

  boolean serverRunning = isServerRunning("localhost", port);
  System.out.printf("Server running: %s\n", serverRunning);

  new ServerSocket(port); // start the server

  serverRunning = isServerRunning("localhost", port);
  System.out.printf("Server running: %s\n", serverRunning);
}

private static boolean isServerRunning(String address, int port) throws IOException {
  try(Socket clientApp = new Socket(address, port)) {
    return true;
  } catch (java.net.ConnectException e) {
    return false;
  }
}
SireInsectus
  • 137
  • 1
  • 3
  • It depends on part on which libraries you are using, but with a simple library like `Socket` or `ServerSocket`, you cannot just connect. A failed connect will throw an exception and you will need to distinguish between a `UnknownHostException`, `NullPointerExcepiton` or `ConnectException` (for example) so as to properly decide how to respond. With that, you also have a socket connection that has to be closed. The necessity of the try-catch is really the only overhead - the actual connection is one line of code. – SireInsectus Dec 15 '15 at 17:13