java - 检查您要连接的端口是否正在使用

标签 java sockets client-server port

所以我有一个服务器客户端程序,它可以捕获屏幕并将其显示在您的屏幕上。 我想在主要部分验证我想要连接的端口是否正在使用并打印一些相关消息..

服务器:

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();

       }
}

客户:

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();
        }
    }
}

最佳答案

如果客户端和服务器在同一个盒子上,那么您可以使用绑定(bind)到现有端口并检查特定异常的策略。

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;
  }
}

如果服务器位于另一个机器上(很可能是这种情况),那么您可以遵循类似的策略,而不是查找 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;
  }
}

关于java - 检查您要连接的端口是否正在使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34272602/

相关文章:

java - EntityManager 生命周期和持续的客户端-服务器-通信

java - 套接字上的 InputStreamReader 未完全读取 POST 请求

javascript - 如何在socket.io中的断开事件上获取断开连接的客户端的套接字ID

java - 更改所选 jbutton 的边框颜色而不命名按钮

java - 可以使用重复继承来缩小类吗?

java - 如何在一个下拉列表中显示绑定(bind)在一起的 2 个元素

c - 哪个函数告诉我内核将本地套接字绑定(bind)到哪个地址?

java - 如何通过java中的套接字发送html文件及其图像

c - 关于集群客户端服务器通信的任何建议。方法?

java - While 循环没有按应有的方式工作