写这个实验的时候坐了很久的牢,遇到了很多匪夷所思的问题,要玉玉了。不过收获也挺多的,验收时对答如流,写出来希望能给大家一些参考。
代理服务器的原理很简单,就是作为客户端和服务器端的中继点,接收到客户端的请求后解析报文、进行一些处理,之后转发给服务器或者是用自己的缓存,再然后把服务器发来的响应报文发回浏览器。
开始前的准备,打开服务器代理设置好代理地址和端口号,并且给我的博客点一个赞。

首先是建立一个套接字用来监听请求,端口就是刚刚设置的端口号。
int port = 8080;
ServerSocket server= new ServerSocket(port);
System.out.println("启动服务器");
System.out.println("客户端:"+server.getInetAddress().getLocalHost()+"已连接到服务器");
int index=0;
接下来的所有代码都在一个while(true)的大循环里,我是纯纯的面向过程编程,大家不要学。。。
当监听到一个请求时,就新建一个套接字专门处理这个请求,然后获取代理服务器和浏览器端之间的输入流和输出流。有一点需要解释一下,输入流和输出流是相对于程序而言的,在这个套接字里也就是对于我们的代理服务器的输入流是浏览器的输出,代理服务器的输出流是浏览器的输入。
index++;
Socket s = server. Accept();
System.out.println("第"+index+"条请求:");
OutputStream output = null;
InputStream input = null;
output = s.getOutputStream();
input = s.getInputStream();
在解析报文之前,就可以进行用户过滤了。方法是获得访问的IP地址,与本机地址比对(毕竟只有本机会访问代理服务器),如果相同就给浏览器返回一个h标签的报文。
boolean ifblockuser = false;
if(ifblockuser)
{
if(s.getInetAddress().getLocalHost().getHostAddress().equals("192.168.32.1"))
{
String body = "<h1>你不许上网</h1>";
String response = "HTTP/1.1 200 ok\r\n" +
"Content-Length: " + body.getBytes().length + "\r\n" +
"Content-Type: textml; charset-utf-8\r\n" +
"\r\n" +
body + "\r\n";
System.out.println("已屏蔽用户");
output.write(response.getBytes());
//按照协议,将返回请求由outputStream写入
output. flush();
continue;
}
}
要注意的是有时候访问地址不是192.168.32.1,大概是因为有其他的应用进程先占用了,这时候就看一下之前打印出来的信息,修改一下就好了。
现在就可以解析浏览器发来的报文了,不过我这里遇到了一点小问题,就是readline函数的阻塞问题,有时候请求会卡住,到最后也不知道怎么正确解决,就只能重启或者等一会,还好验收的时候没出岔子。还有一件事,一般http请求的端口号都是80,但在报文里是不会出现的,直接初始化出来就好了。
String type = null , dsthost = null , URL = null , dstaddr = null;
int dstport = 80;
int flag=1;
StringBuilder header = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String readLine = br.readLine();
while (readLine != null && !readLine.equals("")) {
if(flag==1)
//第一行获取url和请求类型
{
type = readLine.split(" ")[0];
URL = readLine.split(" ")[1];
flag = 0;
}
String[] s1=readLine.split(": ");
for(int i=0;i<s1.length;i++){
if(s1[i].equals("Host"))
{
dstaddr=s1[i+1];
}
}
header.append(readLine).append("\r\n");
readLine = br.readLine();
}
//解析首部完成
获得URL后就可以进行网站钓鱼了,同时我也把https的请求过滤掉了(端口是443的请求),因为代理不了,还会打印出一大坨信息看着很烦。转到钓鱼网站后有图片加载不出来是正常的,因为我们只发了一次请求,后续的一些图片请求没有发。改了很长时间也没有实现完整的网站显示,很烦躁,结果验收时发现大家都是这样的。
if(URL==null)
{
continue;
}
if(URL.contains("443"))
{
System.out.println(URL+" 是 https");
continue;
}
if(URL.contains("yzb.hit.edu.cn"))
{
System.out.println("钓到鱼了");
dstaddr="hituc.hit.edu.cn";
header= new StringBuilder("GET http://hituc.hit.edu.cn/ HTTP/1.1\n"+
"Host: hituc.hit.edu.cn\n" +
"Proxy-Connection: keep-alive\n" +
"Upgrade-Insecure-Requests: 1\n" +
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.53\n" +
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\n" +
"Accept-Encoding: gzip, deflate\n" +
"Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6\n"+"\n");
}
然后要进行的是把目的地址和端口号分离出来(不过似乎没什么太大的用处,懒得改了怕出错),以及网站过滤,这里也是构造报文返回一个h标签。
if (dstaddr.split(":").length > 1) {//代表包含端口号
dstport = Integer.valueOf(dstaddr.split(":")[1]);
}
dsthost = dstaddr.split(":")[0];
//获取目的地址和端口号
header.append("\r\n");
if(dstaddr.contains("jwc.hit.edu.cn")){
//将today.hit.edu.cn作为过滤对象
System.out.println(type);
System.out.println(URL);
String body = "<h1>你不许访问这个网站</h1>";
String response = "HTTP/1.1 200 ok\r\n" +
"Content-Length: " + body.getBytes().length + "\r\n" +
"Content-Type: textml; charset-utf-8\r\n" +
"\r\n" +
body + "\r\n";
System.out.println("用户访问了jwc.hit.edu.cn,已拒绝");
output.write(response.getBytes());
//按照协议,将返回请求由outputStream写入
output.flush();
s.close();
continue;
}
然后就是最主要的部分了,用于实现缓存以及报文的转发和响应。中间的if嵌套有点多,我懒就直接分段贴了,括号肯定是对应不上的,大家复制代码请到最后的源码端去看,这里主要进行解释。首先判断地址不空,就建立一个和目的服务器的套接字,然后还是获取输入流和输出流。之前提到过了,输入输出流是相对于程序而言的,所以这里的输入流是目的服务器的响应,输出流是向目的服务器的发送。
if(dsthost!=null && !dsthost.equals(""))
{
Socket proxy = new Socket(dsthost,dstport);
OutputStream proxyOut = proxy.getOutputStream();
InputStream proxyIn = proxy.getInputStream();
对于请求需要分为两类,GET请求和其他请求,这是出于缓存的考虑,如果是GET请求就需要判断一下代理服务器有没有相应缓存,如果是其他的请求直接转发就好了。指定缓存文件夹之后,循环读取每个文件的第一行和URL能否对应上,如果对应上了就说明缓存命中(文件的第一行是存缓存的时候特地写入的,就是为了查的时候方便)。另外记得改路径,验收时旁边的大哥就因为找不到缓存存到了哪里而被拷打。。。
if (type.equals("GET")) {
boolean ifhasfile = false;
System.out.println(dsthost);
String dir ="C:\\Users\\10139\\eclipse-workspace\\CNLAB1\\src\\cache\\"+ dsthost+index +".txt";
File file = new File(dir);
File folder = new File("C:\\Users\\10139\\eclipse-workspace\\CNLAB1\\src\\cache");
for(File file0:folder.listFiles())
{
BufferedReader fileReader=new BufferedReader(new InputStreamReader(new FileInputStream(file0)));
if(fileReader.readLine().equals(URL))//缓存命中
{
System.out.println(URL+"--> hit!缓存命中");
ifhasfile = true;
file = file0;
break;
}
}
缓存命中之后还要做的是向服务器核对是否有更新,做法是提取缓存中的Date项,构造“If-modified-since”+Date的报文,向服务器发送,得到服务器的响应后就知道有没有更新了。之前没有提到的是怎样进行输入输出流的发送,输入输出流都是传输的字节,所以在write的时候要用getbyte方法转为字节流,最后flush(这个词好形象,像马桶一样)就把报文冲走了,flush之前可以write很多次。
if(ifhasfile)
{
Scanner sc =new Scanner (new FileReader(file));
String line,date=null;
while(sc.hasNextLine())
{
line = sc.nextLine();
if(line.contains("Date"))
{
date = line.substring(6);
}
}
StringBuffer ifGetReqBuffer = new StringBuffer();
ifGetReqBuffer.append("GET " + URL + " HTTP/1.1\r\n");
ifGetReqBuffer.append("Host: " + dsthost + ":" + dstport + "\r\n");
ifGetReqBuffer.append("If-modified-since: " + date + "\r\n");
ifGetReqBuffer.append("\r\n");
String ifGetReq = ifGetReqBuffer.toString();
proxyOut.write(ifGetReq.getBytes());
proxyOut.flush();
之后就要获得服务器的响应了,如果没更新会返回一个304,有更新的话就是正常的200,所以可以接收比较小的一部分报文,判断里面含不含304,如果含的话就直接把缓存发给浏览器就好了,要是不含的话还得把服务器的响应读完,更新缓存并转发。
在循环读取响应报文之前,我写了一个shutdownOutput,这是因为输出流不关闭的话,服务器就不知道我们也没有发完请求,他那边也不会告诉我们他发完了(就是read函数返回-1),这就会造成read函数阻塞,循环就凯住了,体现在浏览器处就是加载出来一部分内容但是一直转圈圈。这个问题困扰了我好久,都要玉玉了,也是坐牢将近一周的罪魁祸首,不过这也和网安的三大寄一周之内都要实验并且还撞上了计网翻转课堂的原因有关系,小小的吐槽一下,有些跑题。另外bytes数组的大小似乎也会产生一些影响,在刚开始我还没写缓存的时候,用1024会导致有的网站加载不出图片,设为1就行,不过写完缓存之后好像就没这个问题了,而且改来改去中间还睡了好多觉,所以实在记不清哪个版本对应什么情况了,大家可以自己摸索一下。
byte[] tempBytes = new byte[30];
int len = proxyIn.read(tempBytes);
String res = new String(tempBytes, 0, len);
if(res.contains("304"))
{
System.out.println("缓存内容未更新,直接使用");
BufferedInputStream inputStream=new BufferedInputStream(new FileInputStream(file));
String pad=URL+"\r\n";
inputStream.read(pad.getBytes());
int length=-1;
byte[] bytes=new byte[1024];
proxy.shutdownOutput();
while((length=inputStream.read(bytes))!=-1){
output.write(bytes,0,length);
}
output.flush();
}
else
{
System.out.println("缓存内容更新,重新缓存并使用");
file.delete();
file.createNewFile();
FileOutputStream outputStream=new FileOutputStream(file);
String pad=URL+"\r\n";
outputStream.write(pad.getBytes("utf-8"));//将URL作为缓存文件的第一行
outputStream.write(tempBytes,0,len);
output.write(tempBytes,0,len);
proxy.shutdownOutput();
BufferedInputStream inputStream=new BufferedInputStream(proxyIn);
byte[] buf = new byte[1024];
int size = 0;
while (( size = inputStream.read(buf)) != -1) {
output.write(buf,0,size);
outputStream.write(buf,0,size);
}
output.flush();
outputStream.flush();
}
}
然后是缓存不命中的情况,就新建文件把服务器响应报文写进去,同时转发给浏览器就好了。要注意记得在第一行写URL,方便之前查找缓存是否存在。
else
{
proxyOut.write(header.toString().getBytes("utf-8"));
proxyOut.flush();
proxy.shutdownOutput();
//如果缓存不存在,则将服务器传来的数据传给客户端并且缓存
System.out.println(URL+" miss!缓存未命中");
file.createNewFile();
FileOutputStream outputStream=new FileOutputStream(file);
String pad=URL+"\r\n";
outputStream.write(pad.getBytes("utf-8"));//将URL作为缓存文件的第一行
BufferedInputStream inputStream=new BufferedInputStream(proxyIn);
byte[] buf = new byte[1024];
int size = 0;
while (( size = inputStream.read(buf)) != -1) {
output.write(buf,0,size);
outputStream.write(buf,0,size);
}
System.out.println("okk");
output.flush();
outputStream.flush();
}
}
}
最后就是把其他类型的请求发给服务器再响应回浏览器就结束啦,撒花!
else
{
Socket proxy = new Socket(dsthost,dstport);
OutputStream proxyOut = proxy.getOutputStream();
InputStream proxyIn = proxy.getInputStream();
proxyOut.write(header.toString().getBytes());
proxyOut.flush();
proxy.shutdownOutput();
BufferedInputStream inputStream=new BufferedInputStream(proxyIn);
byte[] buf = new byte[1];
int size = 0;
while (( size = inputStream.read(buf)) != -1) {
output.write(buf,0,size);
}
output.flush();
}
s.close();
}
最后的最后说一下我没有解决的问题,就是有的工大网站我确实访问不进去,好像其他同学用C写的是可以进去的,比如今日哈工大和哈工大官网,我也不知道是什么原因,验收的时候灵活选择了一下演示的网页,助教也不会特意让我访问别的网站。哦对,我测试没问题的是研究生网、本科生网、教务处、jwts和jwes,但是要是点里面的链接有可能访问不了,不过也没有验收的这么细就是了。最后还是想说我的代码写的很粗糙,但能跑通,希望能给大家一些帮助。
源码:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.net.InetAddress;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Proxy;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SocketServer {
public static void main(String[] args) {
try {
int port = 8080;
ServerSocket server= new ServerSocket(port);
System.out.println("启动服务器");
System.out.println("客户端:"+server.getInetAddress().getLocalHost()+"已连接到服务器");
int index=0;
while(true)
{
index++;
Socket s = server.accept();
System.out.println("第"+index+"条请求:");
OutputStream output = null;
InputStream input = null;
output = s.getOutputStream();
input = s.getInputStream();
boolean ifblockuser = false;
if(ifblockuser)
{
if(s.getInetAddress().getLocalHost().getHostAddress().equals("192.168.32.1"))
{
String body = "<h1>你不许上网</h1>";
String response = "HTTP/1.1 200 ok\r\n" +
"Content-Length: " + body.getBytes().length + "\r\n" +
"Content-Type: textml; charset-utf-8\r\n" +
"\r\n" +
body + "\r\n";
System.out.println("已屏蔽用户");
output.write(response.getBytes());
//按照协议,将返回请求由outputStream写入
output.flush();
continue;
}
}
String type = null , dsthost = null , URL = null , dstaddr = null;
int dstport = 80;
int flag=1;
StringBuilder header = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String readLine = br.readLine();
while (readLine != null && !readLine.equals("")) {
if(flag==1)
//第一行获取url和请求类型
{
type = readLine.split(" ")[0];
URL = readLine.split(" ")[1];
flag = 0;
}
String[] s1=readLine.split(": ");
for(int i=0;i<s1.length;i++){
if(s1[i].equals("Host"))
{
dstaddr=s1[i+1];
}
}
header.append(readLine).append("\r\n");
readLine = br.readLine();
}
//解析首部完成
if(URL==null)
{
continue;
}
if(URL.contains("443"))
{
System.out.println(URL+" 是 https");
continue;
}
if(URL.contains("yzb.hit.edu.cn"))
{
System.out.println("钓到鱼了");
dstaddr="hituc.hit.edu.cn";
header= new StringBuilder("GET http://hituc.hit.edu.cn/ HTTP/1.1\n"+
"Host: hituc.hit.edu.cn\n" +
"Proxy-Connection: keep-alive\n" +
"Upgrade-Insecure-Requests: 1\n" +
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.53\n" +
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\n" +
"Accept-Encoding: gzip, deflate\n" +
"Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6\n"+"\n");
}
//钓鱼网站
if (dstaddr.split(":").length > 1) {//代表包含端口号
dstport = Integer.valueOf(dstaddr.split(":")[1]);
}
dsthost = dstaddr.split(":")[0];
//获取目的地址和端口号
header.append("\r\n");
if(dstaddr.contains("jwc.hit.edu.cn")){
//将today.hit.edu.cn作为过滤对象
System.out.println(type);
System.out.println(URL);
String body = "<h1>你不许访问这个网站</h1>";
String response = "HTTP/1.1 200 ok\r\n" +
"Content-Length: " + body.getBytes().length + "\r\n" +
"Content-Type: textml; charset-utf-8\r\n" +
"\r\n" +
body + "\r\n";
System.out.println("用户访问了jwc.hit.edu.cn,已拒绝");
output.write(response.getBytes());
//按照协议,将返回请求由outputStream写入
output.flush();
s.close();
continue;
}
System.out.println(type+"->"+URL);
System.out.println("-----------");
if(dsthost!=null && !dsthost.equals(""))
{
Socket proxy = new Socket(dsthost,dstport);
OutputStream proxyOut = proxy.getOutputStream();
InputStream proxyIn = proxy.getInputStream();
if (type.equals("GET")) {
boolean ifhasfile = false;
System.out.println(dsthost);
String dir ="C:\\Users\\10139\\eclipse-workspace\\CNLAB1\\src\\cache\\"+ dsthost+index +".txt";
File file = new File(dir);
File folder = new File("C:\\Users\\10139\\eclipse-workspace\\CNLAB1\\src\\cache");
for(File file0:folder.listFiles())
{
BufferedReader fileReader=new BufferedReader(new InputStreamReader(new FileInputStream(file0)));
if(fileReader.readLine().equals(URL))//缓存命中
{
System.out.println(URL+"--> hit!缓存命中");
ifhasfile = true;
file = file0;
break;
}
}
if(ifhasfile)
{
Scanner sc =new Scanner (new FileReader(file));
String line,date=null;
while(sc.hasNextLine())
{
line = sc.nextLine();
if(line.contains("Date"))
{
date = line.substring(6);
}
}
StringBuffer ifGetReqBuffer = new StringBuffer();
ifGetReqBuffer.append("GET " + URL + " HTTP/1.1\r\n");
ifGetReqBuffer.append("Host: " + dsthost + ":" + dstport + "\r\n");
ifGetReqBuffer.append("If-modified-since: " + date + "\r\n");
ifGetReqBuffer.append("\r\n");
String ifGetReq = ifGetReqBuffer.toString();
proxyOut.write(ifGetReq.getBytes());
proxyOut.flush();
byte[] tempBytes = new byte[30];
int len = proxyIn.read(tempBytes);
String res = new String(tempBytes, 0, len);
if(res.contains("304"))
{
System.out.println("缓存内容未更新,直接使用");
BufferedInputStream inputStream=new BufferedInputStream(new FileInputStream(file));
String pad=URL+"\r\n";
inputStream.read(pad.getBytes());
int length=-1;
byte[] bytes=new byte[1024];
proxy.shutdownOutput();
while((length=inputStream.read(bytes))!=-1){
output.write(bytes,0,length);
}
output.flush();
}
else
{
System.out.println("缓存内容更新,重新缓存并使用");
file.delete();
file.createNewFile();
FileOutputStream outputStream=new FileOutputStream(file);
String pad=URL+"\r\n";
outputStream.write(pad.getBytes("utf-8"));//将URL作为缓存文件的第一行
outputStream.write(tempBytes,0,len);
output.write(tempBytes,0,len);
proxy.shutdownOutput();
BufferedInputStream inputStream=new BufferedInputStream(proxyIn);
byte[] buf = new byte[1024];
int size = 0;
while (( size = inputStream.read(buf)) != -1) {
output.write(buf,0,size);
outputStream.write(buf,0,size);
}
output.flush();
outputStream.flush();
}
}
else
{
proxyOut.write(header.toString().getBytes("utf-8"));
proxyOut.flush();
proxy.shutdownOutput();
//如果缓存不存在,则将服务器传来的数据传给客户端并且缓存
System.out.println(URL+" miss!缓存未命中");
file.createNewFile();
FileOutputStream outputStream=new FileOutputStream(file);
String pad=URL+"\r\n";
outputStream.write(pad.getBytes("utf-8"));//将URL作为缓存文件的第一行
BufferedInputStream inputStream=new BufferedInputStream(proxyIn);
byte[] buf = new byte[1];
int size = 0;
while (( size = inputStream.read(buf)) != -1) {
output.write(buf,0,size);
outputStream.write(buf,0,size);
}
System.out.println("okk");
output.flush();
outputStream.flush();
}
}
}
else
{
Socket proxy = new Socket(dsthost,dstport);
OutputStream proxyOut = proxy.getOutputStream();
InputStream proxyIn = proxy.getInputStream();
proxyOut.write(header.toString().getBytes());
proxyOut.flush();
proxy.shutdownOutput();
BufferedInputStream inputStream=new BufferedInputStream(proxyIn);
byte[] buf = new byte[1];
int size = 0;
while (( size = inputStream.read(buf)) != -1) {
output.write(buf,0,size);
}
output.flush();
}
s.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
5141




被折叠的 条评论
为什么被折叠?



