2016-01-31 38 views
0

我想寫一個簡單的代理服務器,並且我在網上發現了這個代碼,我只想嘗試運行它看看它是否工作,但是當它創建一個新的套接字時, ConnectException表示連接被拒絕。我使用'localhost'作爲主機,我嘗試了幾個不同的端口,但沒有任何作用。這裏有什麼問題,是代碼還是我的機器?Java新的套接字連接被拒絕

public static void runServer(String host, int remotePort, int localPort) throws IOException { 

    // Create the socket for listening connections 
    ServerSocket mySocket = new ServerSocket(localPort); 

    final byte[] request = new byte[1024]; 
    byte[] reply = new byte[4096]; 

    while (true) { 
     Socket client = null, server = null; 

     try { 
      client = mySocket.accept(); 

      final InputStream streamFromClient = client.getInputStream(); 
      final OutputStream streamToClient = client.getOutputStream(); 

      try { 
       server = new Socket(host, remotePort); 
      } catch (IOException e) { 
       PrintWriter out = new PrintWriter(streamToClient); 
       out.print("Proxy server cannot connect to " + host + ":" 
       + remotePort + ":\n" + e + "\n"); 
       out.flush(); 
       client.close(); 
       continue; 
      } 

      final InputStream streamFromServer = server.getInputStream(); 
      final OutputStream streamToServer = server.getOutputStream(); 

      Thread t = new Thread() { 
       public void run() { 
        int bytesRead; 
        try { 
         while ((bytesRead = streamFromClient.read(request)) != -1) { 
          streamToServer.write(request, 0, bytesRead); 
          streamToServer.flush(); 
         } 
        } catch (IOException e) { 
        } 
       } 
      }; 

      t.start(); 

      int bytesRead; 
      try { 
       while ((bytesRead = streamFromServer.read(reply)) != -1) { 
        streamToClient.write(reply, 0, bytesRead); 
        streamToClient.flush(); 
       } 
      } catch (IOException e) { 
      } 
      streamToClient.close(); 

     } catch (IOException e) { 
      System.err.println(e); 
     } finally { 
      try { 
       if (server != null) 
        server.close(); 
       if (client != null) 
        client.close(); 
      } catch (IOException e) { 
      } 
     } 
    } 

回答

-1

您需要設置超時而閱讀從插座的數據,有可用的例子here

+0

垃圾。你甚至不能設置超時,更不用說從套接字中讀取任何東西,更不用說得到一個超時異常,直到你有套接字,並且OP沒有套接字:他有'連接被拒絕'。你引用的答案是(a)關於UDP和(b)錯誤。 – EJP

0

「連接被拒絕」的意思正好一件事:什麼也沒有在IP監聽:端口,你試圖連接到。所以這是錯的。解決方法是正確的,或者如果服務器尚未啓動,則啓動服務器。

+0

我正在使用本地主機,所以我不知道你的意思是'啓動服務器,如果它沒有啓動'。我究竟需要做什麼? –

+0

我怎麼知道?這是你的服務器。對於您所引用的文字我沒有發現任何不清楚的地方。 – EJP