簡體   English   中英

Java Socket:我試圖在一個范圍之間生成隨機端口號,但是連接被拒絕,但是當我使用整數時,它可以工作

[英]Java Socket : I'm trying to generate random port numbers between a range, but connection is refused, but when I'm using a integer, it works

客戶:

public class FileClient {  

static int Min = 1050;
static int Max = 15000;
static int PORT = Min + (int)(Math.random() * ((Max - Min) + 1));

    public static void main(String[] args) throws IOException {  
        Socket sock = new Socket("localhost", PORT);  
        if (PORT>=2000&&PORT<=2050) {
            System.out.println("The rare disconnection");
            sock.close();
        }
        System.out.println("Connection Opened");
        // sendfile  
        File myFile = new File("input.txt");  
        byte[] mybytearray = new byte[(int) myFile.length()];  
        FileInputStream fis = new FileInputStream(myFile);  
        BufferedInputStream bis = new BufferedInputStream(fis);  
        System.out.println("Input Stream Opened");
        bis.read(mybytearray, 0, mybytearray.length);  
        OutputStream os = sock.getOutputStream();  
        os.write(mybytearray, 0, mybytearray.length);  
        System.out.println("Data written to output file");
        os.flush();  
        bis.close();  
        System.out.println("Input Stream Closed");
        sock.close();  
        System.out.println("Connection Closed");
    }  
}  

服務器:

public class FileServer {      

   public static void main (String[] args ) throws IOException {     
      int XPORT = FileClient.PORT;
      int bytesRead;  
      ServerSocket serverSocket = new ServerSocket(XPORT);
      System.out.println("Listening for a client");
      while(true) {  
         Socket clientSocket = null;  
         clientSocket = serverSocket.accept();  
         InputStream in = clientSocket.getInputStream();  
         // Writing the file to disk  
         // Instantiating a new output stream object  
         OutputStream output = new FileOutputStream("output.txt");  
         byte[] buffer = new byte[1024];  
         while ((bytesRead = in.read(buffer)) != -1) {  
            output.write(buffer, 0, bytesRead);  
         }  
         // Closing the FileOutputStream handle  
         output.close();  
      }
   }
} 

Java套接字:我試圖在一個范圍之間生成隨機端口號,但是連接被拒絕,但是當我使用整數時,它可以工作。 這是為一個價值而努力。 我希望服務器拒絕幾個端口號的連接(例如:2000-2100),並希望連接被接受並且文件傳輸完成。 當使用整數時,我的文件傳輸效果很好。

運行客戶端時,您會得到一個隨機數。 運行服務器時,您會得到另一個。 他們幾乎可以肯定是不同的。 沒有理由期望它能奏效,也沒有理由嘗試。 使用固定的端口號。 有很多可用的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM