-
实现一个简易的Java代理服务器源代码
资源介绍
基本原理:
代理服务器打开一个端口接收浏览器发来的访问某个站点的请求,从请求的字符串中解析出用户想访问哪个网页,让后通过URL对象建立输入流读取相应的网页内容,最后按照web服务器的工作方式将网页内容发送给用户浏览器
源程序:
import java.net.*;
import java.io.*;
public class MyProxyServer
{
public static void main(String args[])
{
try
{
ServerSocket ss=new ServerSocket(8080);
System.out.println("proxy server OK");
while (true)
{
Socket s=ss.accept();
process p=new process(s);
Thread t=new Thread(p);
t.start();
}
}
catch (Exception e)
{
System.out.println(e);
}
}
};
class process implements Runnable
{
Socket s;
public process(Socket s1)
{
s=s1;
}
public void run()
{
String content=" ";
try
{
PrintStream out=new PrintStream(s.getOutputStream());
BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
String info=in.readLine();
System.out.println("now got "+info);
int sp1=info.indexOf(' ');
int sp2=info.indexOf(' ',sp1+1);
String gotourl=info.substring(sp1,sp2);
System.out.println("now connecting "+gotourl);
URL con=new URL(gotourl);
InputStream gotoin=con.openStream();
int n=gotoin.available();
byte buf[]=new byte[1024];
out.println("HTTP/1.0 200 OK");
out.println("MIME_version:1.0");
out.println("Content_Type:text/html");
out.println("Content_Length:"+n);
out.println(" ");
while ((n=gotoin.read(buf))>=0)
{
out.write(buf,0,n);
}
out.close();
s.close();
}
catch (IOException e)
{
System.out.println("Exception:"+e);
}
}
};