我想寫一個簡單的代理服務器,並且我在網上發現了這個代碼,我只想嘗試運行它看看它是否工作,但是當它創建一個新的套接字時, 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) {
}
}
}
垃圾。你甚至不能設置超時,更不用說從套接字中讀取任何東西,更不用說得到一個超時異常,直到你有套接字,並且OP沒有套接字:他有'連接被拒絕'。你引用的答案是(a)關於UDP和(b)錯誤。 – EJP