J2ME写的简单Http服务器,同时是简…

//======================================================================================
//                    File 2: SocketHeader.java     
//
//          A http server/proxy working in port 8088, No right reserved by Dr. Xiaoguo ZHANG
//          Write it just for fun in my spare time. 
//Revision Histry:
//======================================================================================
// because of Sina blog issue, comments are removed automatically, :-(

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import com.sun.midp.lcdui.PhoneDial;
import javax.microedition.io.file.*;

class SocketHeader
{
public
                      static final String HTTP_GET ="GET ";
                      public static final String HTTP_HEAD ="HEAD ";
                      public static final String HTTP_POST ="POST ";
                      public static final String HTTP_PUT ="PUT ";
                      public static final String HTTP_CONNECT = "CONNECT ";
                      public static final String      DEFAULT_HTTP_PORT = ":80";
                      public static final String      HTTP_PORT_SEPERATOR = ":";
                      public static final String HTTP_HOST = "\r\nHost: ";
                      public static final String CR_String    = "\r\n";
                      public static final String HTTP_LOCAL_HOST_1 = "127.0.0.1";
                      public static final String HTTP_LOCAL_HOST_2 = "localhost";
                      public static final String HTTP_LOCAL_HOST_3 = "xxx.xxx.xxx.xxx";  // I do not know how to get local address using J2ME
                      public static final String HTTP_REQUEST_ADDR_END = " HTTP/1.";          // end with "HTTP/1.0" or "HTTP/1.1"
                      public static final String HPTP_REQUEST_ADDR_BEGIN = "http://";          // GET/CONNECT
                      public static final String HTTP_DEFAULT_URL              = "/index.html";  // default link in http request

                      // public static final String HTTP_DELETE ="GET ";
                      // delete, Trace and option are not supported
                      //
public SocketHeader()
          {
                // do nothing   
          }
public
        void init(String sHttpHeader)
        {
                      m_sHeader = sHttpHeader;  // conver to byte array and stored in a new array
        }
public
        String getHttpHost()
        {
                      return getHttpHost(m_sHeader);
        }

     
public
        static String getHttpHost(String sHttpHeader)
        {
                      int host_pos = sHttpHeader.indexOf(HTTP_HOST) + HTTP_HOST.length();
                      int cr_pos = sHttpHeader.indexOf(CR_String,host_pos);
                      String host = sHttpHeader.substring(host_pos,cr_pos);
                      if( host.indexOf(HTTP_PORT_SEPERATOR) == -1)  // no port in the host string, append 80
                      {
                                host = host + DEFAULT_HTTP_PORT;  // append ":80"
                      }
                   
                      // now let's check whether this is a CONNECT http request
                      if(sHttpHeader.indexOf(SocketHeader.HTTP_CONNECT) == 0) // if CONNECT link, we have to use http address in connect
                      {
                            // try to get host and port directly
                          int from = SocketHeader.HTTP_CONNECT.length();
                          int to = sHttpHeader.indexOf(SocketHeader.HTTP_REQUEST_ADDR_END);
   
                          String host1 = sHttpHeader.substring(from,to);
                          try
                          {
                                host1 = host1.trim();
                                if( host1.indexOf(HTTP_PORT_SEPERATOR) != -1)  // port in the host string, append 80
                                  {
                                        host = host1;
                                  }
                          }
                          catch(Exception e)
                          {
                                      e.printStackTrace();
                          }
                      }
                   
                      return host;                           
        }
public
        static boolean isHttpReq(String sReq)
        {
                int get_pos = sReq.indexOf(HTTP_GET);
                int head_pos = sReq.indexOf(HTTP_HEAD);   
                int post_pos = sReq.indexOf(HTTP_POST);
                int put_pos = sReq.indexOf(HTTP_PUT);
                int connect_pos = sReq.indexOf(HTTP_CONNECT);
             
                return ( (get_pos == 0) ||
                                  (put_pos == 0) ||
                                  (post_pos == 0) ||
                                  (head_pos == 0) ||
                                  (connect_pos == 0));
        }

protected static void DEBUG(String s )
      {
              System.out.println(s);   
      }

protected
        String m_sHeader;
};




class NetworkProxy
{
//public
      public static final int PROXY_MODE_USB  = 0;
      public static final int PROXY_MODE_NET  = 1;
      public static String [] BLOCKED_ADDR =
                                      {
                                            "sprintpcs.com",
                                            "sprint",
                                            "x.xxx.xxx"                   
                                      };
   
public static void set_proxy_server(String proxy_server) // if proxy also based on proxy
        {
                m_proxy_addr = proxy_server ;
         

public
        static void setWorkingMode(int mode, int proxy_port, String usb_num) throws IllegalArgumentException
        {
                  m_working_mode = mode;
                  m_proxy_port = proxy_port;

                  if(mode == PROXY_MODE_NET)
                  {
                          // do nothing
                  }
                  else if(mode == PROXY_MODE_USB)
                  {
                          m_usb = usb_num;
                          // now open usb port for listen and writting
                  }
                  else
                  {
                            System.out.println("Error: bad parameters!!!");
                          throw new IllegalArgumentException ();   
                  }
        }
     
public
          static byte[] proxy_http(SocketConnection sc, String http_header)
          {
                   
                      if(m_working_mode == PROXY_MODE_NET)
                      {
                              return  proxyrequest_http_network(sc, http_header);     
                      }
                      else if(m_working_mode == PROXY_MODE_USB)
                      {
                              return  proxyrequest_http_usb(sc, http_header);  
                      }
                      else
                      {
                              return null;   
                      }
          }
          public static byte[] proxy_socekt(SocketConnection sc, String http_header)
          {
                      if(m_working_mode == PROXY_MODE_NET)
                      {
                              return  proxyrequest_socket_network(sc, http_header);     
                      }
                      else if(m_working_mode == PROXY_MODE_USB)
                      {
                              return  proxyrequest_socket_usb(sc, http_header);  
                      }
                      else
                      {
                              return null;   
                      }
          }



protected
          // implement java http server via Java File API, to retrieve local file system
          static byte[] java_http_server(SocketConnection sc1, String http_header)
          {
                      byte[] data = null;
                      // 1. get local file
                      String s_local_file = http_2_local_file(http_header);
                      DEBUG_3(" try to map it to local file system:"+ s_local_file);
                      if(s_local_file == null)
                      {
                              DEBUG_ERROR(" cannot be mapped to local file");
                              return data;   
                      }
                      try
                      {
                              FileConnection fconn = null;
                           
                                // 2. open the file
                                DEBUG_3(" open the local file:"+ s_local_file);
                                                               
                                fconn = (FileConnection)Connector.open(s_local_file);
                                // If no exception is thrown, then the URI is valid, but the file may or may not exist.
                                if (fconn.exists())
                                {
                                        DEBUG_3(" try to read file");
                                        // 3. read the file to byte array
                                        DataInputStream is = fconn.openDataInputStream();
                                        //long size = fconn.availableSize();
                                        //DEBUG_3("filesize =" + size);
                                          ByteArrayOutputStream bs = new ByteArrayOutputStream();
                                          int read_size;
                                          byte[] buffer_read = new byte[ 1024 ];
                                          while( ( read_size = is.read( buffer_read, 0, 1024 ) ) != -1 )
                                          {
                                                bs.write( buffer_read, 0, read_size );
                                                //DEBUG_2(buffer_read.toString());
                                          }
                                              DEBUG_2("try to output to array ...");     
                                              data = bs.toByteArray();
                                              DEBUG_2(data.toString());
                                       
                                          fconn.close();  
                                }
                                else
                                {
                                      //fconn.create();
                                      DEBUG_ERROR(" file not exist ...");
                                }
                      }
                      catch(Exception e)
                      {
                              e.printStackTrace();
                              DEBUG_ERROR(" Failed to read from file ...");
                      }
                      return data;
           
          }
       
          static String http_2_local_file(String http_header)
          {
                  // we only handle the following http Request
                  //                            GET
                  //                            CONNECT
                int get_pos = http_header.indexOf(SocketHeader.HTTP_GET);
                int head_pos = http_header.indexOf(SocketHeader.HTTP_HEAD);   
                int connect_pos = http_header.indexOf(SocketHeader.HTTP_CONNECT);
                String sReturn = null;
             
                if ( (get_pos != 0) && (head_pos != 0) && (connect_pos != 0))
                {
                        return sReturn;
                }
             
                // now try to get local file name
                int from = http_header.indexOf(SocketHeader.HPTP_REQUEST_ADDR_BEGIN);
                int to = http_header.indexOf(SocketHeader.HTTP_REQUEST_ADDR_END);
             
                if( (from < 0) || (from >= to ) ) // no (from <0) mean no "http://" header in the first line, ( from >= to) means somewhere else has http:// string
                {
                      from = 0 - SocketHeader.HPTP_REQUEST_ADDR_BEGIN.length();
                }

                sReturn = http_header.substring(from + SocketHeader.HPTP_REQUEST_ADDR_BEGIN.length(),to);
             
           
                from = sReturn.indexOf("/");
                sReturn = sReturn.substring(from+1, sReturn.length());
             
                if(sReturn.length() == 0)
                {
                        sReturn = "index.html";  
                }
                sReturn = "file:///root1/" + sReturn;// + ",the size of file="+ sReturn.length();       
                   
                DEBUG_3("file_name: "+ sReturn);
                return sReturn;
             
        }

protected
          // if the destination address of this http request is to local machine, if that we will handle this req internally
          // otherwise, we will proxy the request to outside server
          static boolean is_local_http_request(SocketConnection sc, String http_host_addr)
          {

                    String s_local_addr = SocketHeader.HTTP_LOCAL_HOST_3;
                    try
                    {
                              s_local_addr = sc.getLocalAddress();
                    }
                    catch(Exception e)
                    {
                              DEBUG_2("  failed to get local ip address!");
                    }
                                                                     
                    if( (http_host_addr.indexOf(SocketHeader.HTTP_LOCAL_HOST_1) != -1)  ||
                            (http_host_addr.indexOf(SocketHeader.HTTP_LOCAL_HOST_2) != -1)  ||
                            //(http_host_addr.indexOf(SocketHeader.HTTP_LOCAL_HOST_3) != -1)  ||
                            (http_host_addr.indexOf(s_local_addr) != -1)
                              )
                        {
                              return true;
                        }
                        else
                        {
                              return false;  
                        }
                   
          }

protected
          static byte[] proxyrequest_http_network(SocketConnection sc1, String http_header)
          {
                        byte[] data = null;
                        try
                        {
                           

                                      if(is_local_http_request(sc1,http_header))
                                      {

                                              return java_http_server(sc1, http_header);                                              // local http server
                                      }
                                   
                                      DEBUG_2("      !!! not local request !!!");


                                      // 1. create socket connection for http request
                                      String sConn = "socket://"+ SocketHeader.getHttpHost(http_header);
                                      // 2. check whether blocked website, if that, directly return data as null
                                      int block_addr_num = NetworkProxy.BLOCKED_ADDR.length;
                                      for(int i = 0; i < block_addr_num;i++)
                                      {
                                              if (      sConn.indexOf(NetworkProxy.BLOCKED_ADDR[i]) != -1)
                                              {
                                                      DEBUG_2("Blocked addr:" + sConn);
                                                      return data;  // directly return data   
                                              }
                                                                       
                                   
                                      // use unicomm gateway to get data
                                   
                                      if(m_proxy_addr != null)
                                      {
                                                sConn = m_proxy_addr;  // connect proxy, use use the proxy of the proxy to request data
                                      }
                                   

                                   
                                 
                                      DEBUG_2("try to open:" + sConn);
                                      SocketConnection sc_proxy = (SocketConnection)Connector.open(sConn);  //connect to the host
                                      //DEBUG_2("socket connected ...");
                                      OutputStream os = sc_proxy.openOutputStream();
                                      //DEBUG_2("open outputstream ...");
                                      DEBUG_2(" write http header to server:" + sConn);
                                   
                                      os.write(http_header.getBytes());
                                      os.flush();
                                      //DEBUG_2("write http request header to server ....");
                                   
                                      // finished sending http request, then try to get response from server
                                      InputStream is = sc_proxy.openInputStream();
                                      DEBUG_2("try to read data from server ...");
                                 
                                      ByteArrayOutputStream bs = new ByteArrayOutputStream();
                                      int read_size;
                                      byte[] buffer_read = new byte[ 10240 ];
                                      while( ( read_size = is.read( buffer_read, 0, 10240 ) ) != -1 )
                                      {
                                                //System.out.println( "=========== xxx ================");
                                                bs.write( buffer_read, 0, read_size );
                                                //DEBUG_2(buffer_read.toString());
                                      }
                                      DEBUG_2("try to output to array ...");     
                                      data = bs.toByteArray();
                                      DEBUG_2(data.toString());
                                   
                                     
                      }
                      catch(Exception e)
                      {
                              System.out.println("Error: shit, failed to proxy ...");
                              e.printStackTrace();
                           
                      }
                   
                      return data;
          }
       
          protected static byte[] proxyrequest_http_usb(SocketConnection sc, String http_header)
          {
                        byte[] data = null;
                     
                     
                        return data;
          }
       
          protected static byte[] proxyrequest_socket_network(SocketConnection sc, String http_header)
          {
                        byte[] data = null;
                     
                     
                        return data;               
          }
          protected static byte[] proxyrequest_socket_usb(SocketConnection sc, String http_header)
          {
                        byte[] data = null;
                     
                     
                        return data;               
           
protected static void DEBUG_ERROR(String s)
          {
                  System.out.println("HTTP_PROXY critical error:        " + s);
          }

protected static void DEBUG_2(String s)
          {
                  System.out.println("HTTP_PROXY 2:        " + s);
          }
protected static void DEBUG_3(String s)
          {
                  System.out.println("HTTP_LOCAL 3:        " + s);
          }

protected
          static int m_working_mode = PROXY_MODE_NET; // default mode net mode
          protected static int m_proxy_port = 8088;                        // default proxy port
          protected static String m_usb        = "usb0";                      // default usb connection
       
public static void set_proxy(String s_proxy_addr)
        {
                      m_proxy_addr = s_proxy_addr;
             
        public static void set_http_root_fs(String s_root_fs)
        {
                if(s_root_fs == null)
                {
                      s_root_fs = "";
                }
                m_local_root_fs =  s_root_fs;
        }
public static void set_service_port(String s_port)
      {
              if((s_port == null) || ( s_port == ""))
              {
                      m_service_port = "8088";
               
              else
              {
                      m_service_port = s_port;   
              }
         
public static String get_service_port()
      {
              return m_service_port;
         


protected
      static String m_proxy_addr = null;    // proxy of this proxy, which mean the proxy will go to out side the network through it, only valid when not over usb
      static String m_local_root_fs = "";  // default emptry
      static String m_service_port  = "8088"; // default proxy port for the final user
           
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值