java实现一个简单的代理服务器

这里实现了一个基础的代理服务器,就是socket管道的跳转,但是对于应用中的代理服务器,其中必有很多东西是要注意的,考虑的,这里的代码仅仅是为了使你去了解代理服务器的一个简单流程

代理服务器类


package com.inetAddressTest.proxy;

import jdk.internal.util.xml.impl.Input;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * Created by Administrator on 2017/5/1.
 */
public class MyHttpProxy extends Thread {
    //尝试重新连接次数
    public static int CONNECT_RETRIES=5;
    //尝试重连中间停顿的次数
    public static int CONNECT_PAUSE=5;
    //超时连接时间
    public static int TIME_OUT=50;
    //是否计入日志信息
    public static boolean logging=false;
    //日志输出位置
    public static OutputStream out=null;
    //设置代理服务器地址,默认为本地的8080
    private static InetSocketAddress address=new InetSocketAddress("localhost",8080);
    //设置父类代理服务器的地址
    private static InetSocketAddress pAddress=null;
    //
    private Socket socket;
    public static void setParentProxy(InetSocketAddress address){
        pAddress=address;
    }
    public MyHttpProxy(Socket socket){
        this.socket=socket;
        start();
    }

    public void writeLog(int c, boolean browser) throws IOException {
        out.write(c);
    }

    public void writeLog(byte[] bytes,int offset, int len, boolean browser) throws IOException {
        for (int i=0;i<len;i++) writeLog((int)bytes[offset+i],browser);
    }

    public String proccessHostName(String url,String host,int port,Socket socket){
        DateFormat df=DateFormat.getInstance();
        System.out.println(df.format(new Date()+" "+url+" "+host+" "+port+" "+socket.getInetAddress()));
        return host;
    }

    /**
     * 该方法用于通道的转换
     * @param in0 from
     * @param in1
     * @param out1 to
     * @param out2
     */
    public void pipe(InputStream in0,InputStream in1,OutputStream out1,OutputStream out2){
        int a=0;
        byte[] buff=new byte[1024];

        try {
            while ((a=in0.read(buff))!=-1){
                out1.write(buff,0,a);
                writeLog(buff,0,a,true);
            }
        } catch (IOException e) {
            //捕捉到异常时将流写回原来的流
            try {
                while ((a=in1.read(buff))!=-1){
                    out2.write(buff,0,a);
                    writeLog(buff,0,a,true);
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }


    }
    @Override
    public void run() {
        //被代理服务器的socket
        Socket outBound=null;
        String host="127.0.0.1";
        int port=8900;
        if(pAddress!=null){
            host=pAddress.getHostName();
            port=pAddress.getPort();
        }
        //尝试连接次数
        int retry=CONNECT_RETRIES;
        try {
            while(true){
                try {
                    outBound=new Socket(host,port);
                    break;
                } catch (IOException e) {
                    try {
                        //连接失败后尝试连接等到时间
                        Thread.sleep(CONNECT_PAUSE);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            }

            if(outBound!=null){
                outBound.setSoTimeout(TIME_OUT);
                //转换通道
                pipe(socket.getInputStream(),outBound.getInputStream(),outBound.getOutputStream(),socket.getOutputStream());

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 客服端设置代理对象
     * @param address0  代理服务器地址
     * @param proxy    代理类,可为HttpProxy的子类
     */
    public static void setProxy(InetSocketAddress address0,Class<MyHttpProxy> proxy){
        if(address!=null){
            address=address0;
        }
        ServerSocket serverSocket=null;
        Socket socket=null;

        try {
            serverSocket=new ServerSocket(address.getPort());
            while (true){
                //用反射通过构造函数来得到代理类的实例
                Class[] sarg=new Class[1];
                Object[] oarg=new Object[1];
                sarg[0]=Socket.class;
                try {
                    Constructor<MyHttpProxy> cons=proxy.getDeclaredConstructor(sarg);
                    oarg[0]=serverSocket.accept();
                    cons.newInstance(oarg);//每次接受到连接都要实例化一个对象//实际运用在是否应该考虑一下缓存问题
                } catch (Exception e) {
                    ((Socket)oarg[0]).close();
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println("启动代理服务器");
        MyHttpProxy.logging=true;
        MyHttpProxy.out=System.out;
        MyHttpProxy.setProxy(new InetSocketAddress("localhost",8080),MyHttpProxy.class);
    }
}

被代理类


package com.inetAddressTest.proxy;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator on 2017/5/1.
 */
public class SocketServerTest {
    public static void main(String[] args) throws Exception{
        System.out.println("启动了服务器");
        ServerSocket serverSocket=new ServerSocket(8900);
        while (true){
            Socket socket=serverSocket.accept();
            BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line="";
            while ((line=reader.readLine())!=null){
                System.out.println(line);
            }
        }
    }
}

基本原理: 代理服务器打开一个端口接收浏览器发来的访问某个站点的请求,从请求的字符串中解析出用户想访问哪个网页,让后通过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); } } };
实现一个用于接受邮件的代理服务器需要通过以下步骤: 1. 使用Java Socket编程创建一个服务器端程序,该程序监听特定的端口并接受客户端连接。 2. 通过Java Mail API实现SMTP协议,将接收到的邮件转发到指定的邮件服务器。 3. 对于每封邮件,可以使用Java Mail API将邮件内容存储到本地磁盘或数据库中。 下面是一个简单Java代理服务器代码示例: ```java import java.net.*; import java.io.*; public class MailProxyServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(25); } catch (IOException e) { System.err.println("Could not listen on port: 25."); System.exit(1); } Socket clientSocket = null; System.out.println("Waiting for connection....."); try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } System.out.println("Connection successful"); System.out.println("Waiting for input....."); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Server: " + inputLine); if (inputLine.startsWith("MAIL FROM:")) { // 截取发件人地址 String fromAddress = inputLine.substring(inputLine.indexOf("<") + 1, inputLine.indexOf(">")); System.out.println("From address: " + fromAddress); // 使用Java Mail API将邮件转发到指定的邮件服务器 sendMail(fromAddress, "to@example.com", "Subject", "Body"); } out.println(inputLine); if (inputLine.equals("QUIT")) { break; } } out.close(); in.close(); clientSocket.close(); serverSocket.close(); } private static void sendMail(String fromAddress, String toAddress, String subject, String body) { // 创建邮件会话 Session session = Session.getDefaultInstance(System.getProperties(), null); try { // 创建邮件消息 MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddress)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); message.setSubject(subject); message.setText(body); // 发送邮件 Transport.send(message); System.out.println("Mail sent successfully."); } catch (MessagingException e) { e.printStackTrace(); } } } ``` 注意:这只是一个简单的示例代码,实际应用中需要考虑更多的异常处理、安全和性能问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值