Witam,
Mam problem z poniższym kodem. Aplikacja ta ma stać się docelowo serwerem proxy. Po skompilowaniu kodu i wpisaniu w przeglądarke(firefox) adresu localhost:999/http://www.google.pl kompilator wyrzuca mi błąd java.net.UnknownHostException: localhost:999 miejsce błędu zaznaczyłem komentarzem.
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
class SimpleProxyServer {
public static final int portNumber = 999;
public static void main(String[] args){
SimpleProxyServer proxyServer = new SimpleProxyServer();
proxyServer.start();
}
public void start(){
System.out.println("Starting the SimpleProxyServer ...");
try {
ServerSocket serverSocket = new ServerSocket(MyProxyServer.portNumber,1);
byte[] buffer = new byte[10000];
while(true){
Socket clientSocket = serverSocket.accept();
InputStream bis = clientSocket.getInputStream();
// reading the request and put it into buffer
int n = bis.read(buffer);
String browserRequest = new String(buffer, 0, n);
System.out.println(browserRequest);
System.out.println("aaaa");
// extract the host to connect to
int start = browserRequest.indexOf("Host: ") + 6;
int end = browserRequest.indexOf('\n', start);
String host = browserRequest.substring(start, end - 1);
System.out.println(browserRequest);
System.out.println("Connecting to host " + host);
// forward the response from the proxy to the server
Socket hostSocket = new Socket("host", 80);// TU WYRZUCA BLAD
OutputStream sos = hostSocket.getOutputStream();
System.out.println("Forwarding request to server");
sos.write(buffer, 0, n);
sos.flush();
// forward the response from the server to the browser
InputStream sis = hostSocket.getInputStream();
OutputStream bos = clientSocket.getOutputStream();
System.out.println("Forwarding request from server");
do {
n = sis.read(buffer);
System.out.println("Receiving " + n + " bytes");
if (n > 0) {
bos.write(buffer, 0, n);
}
} while (n > 0);
bos.flush();
hostSocket.close();
clientSocket.close();
System.out.println("End of communication");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Natomiast jak zamienie wskazane miejsce błedu zamieni zmienna host na "localhost" to dostaje błąd java.net.ConnectException: Connection refused: connect.
Proszę o pomoc w rozwiązaniu tego problemu.