import java.io.*;
import java.net.*;
import java.nio.charset.*;
import java.nio.*;
import java.util.regex.*;
public class ProxyFrame
{
ServerSocket ss;
boolean start=true;
int localport=8080;
public ProxyFrame()
{
try
{
ss=new ServerSocket(localport);
while(start)
{
Socket client=ss.accept();
//建立到客户端的管道
InputStream from_client=client.getInputStream();
OutputStream to_client=client.getOutputStream();
//获取客户端的请求
BufferedReader br=new BufferedReader(new InputStreamReader(from_client));
String str=br.readLine();
System.out.println(str);
String urlstr=getURL(str);
System.out.println(urlstr);
URL url=new URL(urlstr);
String host=url.getHost();
System.out.println(host);
int remoteport=url.getPort();
if(remoteport==-1)
{
remoteport=80;
}
System.out.println(remoteport);
new ProxyThread(str,from_client,to_client,host,remoteport);
}
}
catch(Exception ex)
{
System.out.println(ex);
}
}
public String getURL(String str)
{
String str2="";
Pattern p = Pattern.compile("http://[a-z|A-Z]+[.][a-z]+[.][a-z|a-z]+");
Matcher m = p.matcher(str);
boolean result=m.find();
if(result)
{
str2=m.group();
}
return str2;
}
public static void main(String args[])
{
new ProxyFrame();
}
}
import java.net.*;
import java.io.*;
public class ProxyThread implements Runnable
{
String str;
InputStream from_client;
OutputStream to_client;
String host;
int port;
public ProxyThread(String str,InputStream from_client,OutputStream to_client,String host,int port)
{
this.str=str;
this.from_client=from_client;
this.to_client=to_client;
this.host=host;
this.port=port;
Thread t=new Thread(this);
t.start();
}
public void run()
{
try
{
//建立到服务器的管道
Socket server=new Socket(host,port);
InputStream from_server=server.getInputStream();
OutputStream to_server=server.getOutputStream();
//发送请求
int read_byte;
to_server.write(str.getBytes());
to_server.write(' ');
to_server.flush();
to_server.close();
//接收返回
byte[] reply=new byte[4096];
while((read_byte=from_server.read(reply))!=-1)
{
System.out.println(read_byte);
to_client.write(reply,0,read_byte);
to_client.flush();
}
to_client.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
服务器端启动后可以接收来自客户端的请求,但客户端的浏览器状态栏始终显示“正在打开网页.......”,不知哪位大侠可否指点