Search code examples
javaappium

How to check if appium server is already running using java


I'm able to start and stop appium using the below code but i want to know how to check if the server is already running before starting in java. I googled it but i dont seem to find anything relevant any advise on this would be very much appreciated. Thanks in advance. Please find the code below:

package code;

import java.io.File;

import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
import org.openqa.selenium.WebDriver;

public class AppiumServerStartStop
{

   static WebDriver driver;
   static String Appium_Node_Path = "C:\\Program Files\\nodejs\\node.exe";
   static String Appium_JS_Path = "C:\\Users\\Administrator\\AppData\\Local\\Programs\\appium-desktop\\resources\\app\\node_modules\\appium\\lib\\appium.js";
   static AppiumDriverLocalService service;
   static String service_url;

   public static void main(String args[])
      throws Exception
   {
      appiumStart();
   }

   public static void appiumStart() throws Exception
   {

      service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder().usingAnyFreePort().usingDriverExecutable(new File(Appium_Node_Path)).withAppiumJS(new File(Appium_JS_Path)));
      service.start();
      service_url = service.getUrl().toString();
      System.out.println("Appium Service Address : - " + service_url);
      service.stop();
   }
}

Solution

  • I found that snipped on this site:

    public boolean checkIfServerIsRunnning(int port) {
    
        boolean isServerRunning = false;
        ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(port);
            serverSocket.close();
        } catch (IOException e) {
            //If control comes here, then it means that the port is in use
            isServerRunning = true;
        } finally {
            serverSocket = null;
        }
        return isServerRunning;
    }
    

    The logic here is to figure out if the port is in use or not. Generally, the ports that you use with Appium are not used by other applications. So if the port is already in use, it is safe to assume that Appium server is running on the port.