【问题标题】:Check if the port you want to connect to is in use检查您要连接的端口是否正在使用中
【发布时间】:2016-03-20 06:17:58
【问题描述】:

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

服务器:

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

【问题讨论】:

  • 那么问题是什么?
  • 我想在主体部分验证我要连接的端口是否正在使用并打印一些相关消息..
  • stackoverflow.com/questions/2675362/… 可能有与您的问题相关的重要信息
  • 我会在自己设置之前尝试连接到端口:如果端口已打开并且您可以连接到它,那么您会抛出异常。

标签: java sockets client-server port


【解决方案1】:

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

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

【讨论】:

  • 这取决于您使用的库,但是对于像Socket 或ServerSocket 这样的简单库,您不能只连接。连接失败将引发异常,您需要区分UnknownHostException、NullPointerExcepiton 或ConnectException(例如),以便正确决定如何响应。这样,您还有一个必须关闭的套接字连接。 try-catch 的必要性实际上是唯一的开销 - 实际连接是一行代码。
猜你喜欢
  • 2011-10-18
  • 1970-01-01
  • 2012-10-29
  • 2020-08-19
  • 2014-02-23
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
相关资源
最近更新 更多