java編寫簡單實用的類似tomcat的web應用服務器
com.zxy.common.Com_Fun類:通用函數類
com.zxy.common.Com_Para類:全局變量類
com.zxy.common.Init_Page類:初始化全局變量
com.zxy.log.UsAdmin_Log類:錯誤日誌類
com.zxy.main.webAppMain類:主程序入口main函數
com.zxy.task.SelfTimeTask類:定時器任務類
com.zxy.tcp.Request類:加載數據request
com.zxy.tcp.Responst類
com.zxy.tcp.ServerThreadHttp類:多線程tcp通訊
com.zxy.tcp.ServerHandlerHttp類:webpage數據請求處理
測試案例中添加web文件夾,內容放置hplus靜態UI界面內容
com.zxy.common.Com_Fun類:
package com.zxy.common;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class Com_Fun
{
public static String NoNull(Object objTag)
{
if(objTag == null)
return "";
else
return objTag.toString().trim();
}
public static String FloatToStr(float finput)
{
java.math.BigDecimal bg = new java.math.BigDecimal(finput);
return bg.toString();
}
public static String ReplacePath(String loginName, String strValue, int iFlag, int IS_URLENCODE)
{
String strResult = strValue;
if(iFlag == 1)
{
String strG = strValue.replaceAll("src='","src='"
+ Com_Para.HTTP_Path).replaceAll("src=\"","src=\'"
+ Com_Para.HTTP_Path).replaceAll("\"","'");
if(strG.length() > 3)
{
String strAtt = strG.substring(strG.length() - 4,strG.length());
if(strAtt.toLowerCase().equals(".jpg")
|| strAtt.toLowerCase().equals(".gif")
|| strAtt.toLowerCase().equals(".png")
|| strAtt.toLowerCase().equals(".bmp"))
{
strG = Com_Para.HTTP_Path + loginName + "/" + strG;
}
}
strResult = strG;
}
if(IS_URLENCODE == 1)
{
try
{
strResult = Java_encode(URLEncoder.encode(strResult,Com_Para.U_CODE));
}
catch(UnsupportedEncodingException e)
{
}
}
return strResult;
}
public static String Get_New_GUID()
{
return java.util.UUID.randomUUID().toString().toUpperCase();
}
public static float Get_dot_two(float fInput)
{
return (float) (Math.round(fInput * 100) / 100);
}
public static float Get_dot_two(String fInput)
{
return (float) (Math.round(Float.valueOf(fInput) * 100) / 100);
}
public static String DateTimeStr(String DateFormat)
{
return new SimpleDateFormat(DateFormat).format(new Date());
}
public static String DateTimeStrYYYYMMDDHHmmss(String strInput, String DateFormat)
{
SimpleDateFormat df = new SimpleDateFormat(DateFormat);
Date dtREQ_TIME;
try
{
dtREQ_TIME = df.parse(strInput);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dtREQ_TIME);
}
catch(ParseException e)
{
return "1900-01-01 00:00:00";
}
}
public static String DateTimeToStr(Date dtREQ_TIME) throws Exception
{
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dtREQ_TIME);
}
public static Date StrDateTime(String DateFormat, String strInput) throws Exception
{
return new SimpleDateFormat(DateFormat).parse(strInput);
}
// 月份相加
public static String stepMonth(String DateFormat, Date sourceDate, int month) throws Exception
{
Calendar c = Calendar.getInstance();
c.setTime(sourceDate);
c.add(Calendar.MONTH,month);
return new SimpleDateFormat(DateFormat).format(c.getTime());
}
public static String get0X01()
{
byte b1[] =
{ 0x01 };
String str1 = new String(b1);
return str1;
}
public static String get0X02()
{
byte b2[] =
{ 0x02 };
String str2 = new String(b2);
return str2;
}
public static String GetHashTable(Hashtable<String, String> ht, String key)
{
String strResult = "";
if(ht.get(key) == null)
strResult = "";
else
strResult = ht.get(key).toString();
return strResult;
}
public String byte2hex(byte[] b)
{
String hs = "";
String stmp = "";
for(int n = 0;n < b.length;n++)
{
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if(stmp.length() == 1)
{
hs = hs + "0" + stmp;
}else
{
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
public byte[] hex2byte(String hex)
{
byte[] ret = new byte[8];
byte[] tmp = hex.getBytes();
for(int i = 0;i < 8;i++)
{
ret[i] = uniteBytes(tmp[i * 2],tmp[i * 2 + 1]);
}
return ret;
}
public static byte uniteBytes(byte src0, byte src1)
{
byte _b0 = Byte.decode("0x" + new String(new byte[]
{ src0 })).byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[]
{ src1 })).byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
public static String Java_encode(String strInput)
{
return strInput.replaceAll("%27","'").replaceAll("%21","!").replaceAll("%28","(").replaceAll("%29",")").replaceAll("%7E","~").replaceAll("%0D","");// .replaceAll("+","%20");
}
// 獲取絕對路徑
public static String GetAbsPath()
{
String strResult = Com_Para.class.getProtectionDomain().getCodeSource().getLocation().getPath();
int iLength = strResult.lastIndexOf(Com_Para.zxyPath);
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith("win"))
{
if(iLength > 0)
return strResult.substring(1,iLength) + "/";
else
return strResult.substring(1,strResult.length()) + "/";
}else
{
if(iLength > 0)
return strResult.substring(0,iLength) + "/";
else
return strResult.substring(0,strResult.length()) + "/";
}
}
}
com.zxy.common.Com_Para類:全局變量類
package com.zxy.common;
import java.net.Socket;
import java.util.Hashtable;
public class Com_Para
{
// 定時器正在運行標籤
public static boolean bTimeFlag = false;
// 路徑
public static String zxyPath = "/";
// 相對路徑
public static String ApplicationPath = Com_Fun.GetAbsPath();
// 訪問函數名
public static String Inf_Name = "CenterData";
// web文件後綴
public static String[] web_Name =
{ ".html", ".js",
".css", ".jpg", ".gif", ".png", ".svg", ".eot", ".ttf", ".woff2",
".woff", ".ico" };
// 圖片訪問路徑 // 毫秒
public static String HTTP_Path = "";
// 指定跨域訪問IP xxx.xx.xx.xxx 默認爲空 // 1需要
public static String HttpUrl = "";
// 編碼格式
public static String U_CODE = "UTF-8";
// socket統計
public static int socket_count = 0;
// 是否啓用http協議
public static boolean bThread = true;
// web應用服務端口
public static int port = 8089;
// 存儲子設備的IP 和 socket 其中key = clientSocket爲本機作爲客戶端設備socket存儲
public static Hashtable<String, Socket> htServSockets = new Hashtable<String, Socket>();
// 連接服務端的客戶端socket
public static Socket clientSocket = null;
private Com_Para()
{
}
}
com.zxy.common.Init_Page類:初始化全局變量
package com.zxy.common;
public class Init_Page
{
// 讀取初始加載信息
public static void Init_Load()
{
/*全局變量定義*/
//Com_Para.Inf_Name = "";
//Com_Para.HTTP_Path = "";
//Com_Para.U_CODE = "";
}
}
com.zxy.log.UsAdmin_Log類:錯誤日誌類
package com.zxy.log;
import java.io.*;
import com.zxy.common.Com_Fun;
import com.zxy.common.Com_Para;
//錯誤日誌文件,超過1M自動按序號新增日誌文件
public class UsAdmin_Log
{
private StringBuilder strContent = null;
private String strFolder = "";
private String strTFileName = "";
private File fiFile = null;
public StringBuilder getStrContent()
{
return strContent;
}
public void setStrContent(StringBuilder Content)
{
this.strContent = Content;
}
public String getStrFolder()
{
return strFolder;
}
public void setStrFolder(String Folder)
{
this.strFolder = Folder;
}
public String getStrTFileName()
{
return strTFileName;
}
public void setStrTFileName(String TFileName)
{
this.strTFileName = TFileName;
}
public File getFiFile()
{
return fiFile;
}
public void setFiFile(File temfiFile)
{
this.fiFile = temfiFile;
}
public UsAdmin_Log(String strTemFolder, StringBuilder strValue, int Data)
{
this.setStrFolder(strTemFolder + Com_Para.zxyPath + "data");
this.setStrContent(strValue);
}
public UsAdmin_Log(String strTemFolder, StringBuilder strValue)
{
this.setStrFolder(strTemFolder + Com_Para.zxyPath + "log");
this.setStrContent(strValue);
}
public UsAdmin_Log(String strTemFolder, StringBuilder strValue, String strFileName)
{
this.setStrFolder(strTemFolder + Com_Para.zxyPath + "log");
this.setStrContent(strValue);
this.setStrTFileName(strFileName);
}
public void WriteData(String delay_code) throws IOException
{
HadForder();
SaveFileData(delay_code);
}
// 寫日誌文件
public void WriteLog() throws IOException
{
HadForder();
SaveFileDay();
}
public void WriteLogAll(StringBuilder strSub) throws IOException
{
HadForder();
SaveFileDayAll(strSub);
}
// 寫日誌文件
public void WriteLogSub(String strSub) throws IOException
{
HadForder();
SaveFileDay(strSub);
}
public StringBuilder ReadData(String delay_code,String param_name) throws IOException
{
StringBuilder strResult = new StringBuilder();
strTFileName = strFolder + Com_Para.zxyPath + delay_code + ".dat";
fiFile = new File(strTFileName);
FileReader fr = null;
if(!fiFile.exists())
{
strResult.append("{\""
+ param_name
+ "\":[{\"s_result\":\"0\",\"error_desc\":\"數據查詢中或數據結果未生成,請稍候在試"
+ "\"}]}");
//strResult = "數據查詢中,請稍候在試";
}else
{
try
{
fr = new FileReader(strTFileName);
char[] Bytes = new char[(int) fiFile.length()];
if(fr.read(Bytes,0,Bytes.length) > 0)
{
for(int i = 0;i < Bytes.length;i++)
{
strResult.append(Bytes[i]);
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
fr.close();
}
}
return strResult;
}
private void SaveFileData(String delay_code) throws IOException
{
strTFileName = strFolder + Com_Para.zxyPath + delay_code + ".dat";
fiFile = new File(strTFileName);
FileWriter sw = null;
if(!fiFile.exists())
{
fiFile.createNewFile();
sw = new FileWriter(strTFileName,true);
sw.write(strContent.toString());
sw.close();
}else
{
sw = new FileWriter(strTFileName,true);
sw.write(strContent.toString());
sw.close();
}
}
private void SaveFileDayAll(StringBuilder strTContent) throws IOException
{
String strLogName = "";
if(this.getStrTFileName() == "")
strLogName = strFolder + Com_Para.zxyPath + "zxyong_"
+ Com_Fun.DateTimeStr("yyyyMMdd") + "_0.log";
else
strLogName = strFolder + Com_Para.zxyPath + this.getStrTFileName()
+ ".log";
fiFile = new File(strLogName);
long lgSize = 0;
FileWriter sw = null;
if(!fiFile.exists())
{
fiFile.createNewFile();
sw = new FileWriter(strLogName,true);
sw.write("*********" + Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss")
+ "*********\r\n");
sw.write(strContent.toString());
sw.close();
}else
{
lgSize = fiFile.length();
int i = 1;
while(true)
{
if(lgSize > Long.valueOf(1 * 1024 * 1024))
{
if(this.getStrTFileName() == "")
strLogName = strFolder + Com_Para.zxyPath + "zxyong_"
+ Com_Fun.DateTimeStr("yyyyMMdd") + "_"
+ String.valueOf(i) + ".log";
else
strLogName = strFolder + Com_Para.zxyPath
+ this.getStrTFileName()
+ Com_Fun.DateTimeStr("yyyyMMdd") + "_"
+ String.valueOf(i) + ".log";
fiFile = new File(strLogName);
if(!fiFile.exists())
{
fiFile.createNewFile();
sw = new FileWriter(strLogName,true);
sw.write("*********"
+ Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss")
+ "*********\r\n");
sw.write(strContent.toString());
sw.close();
}else
{
lgSize = fiFile.length();
}
}else
{
sw = new FileWriter(strLogName,true);
sw.write("*********"
+ Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss")
+ "*********\r\n");
sw.write(strContent.toString());
sw.close();
break;
}
i++;
}
}
}
// 按日保存日誌文件
private void SaveFileDay(String Sub) throws IOException
{
String strLogName = strFolder + Com_Para.zxyPath + "zxyong_" + Sub
+ Com_Fun.DateTimeStr("yyyyMMdd") + "_0.log";
fiFile = new File(strLogName);
long lgSize = 0;
FileWriter sw = null;
if(!fiFile.exists())
{
fiFile.createNewFile();
sw = new FileWriter(strLogName,true);
sw.write("*********" + Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss")
+ "*********\r\n");
sw.write(strContent.toString());
sw.close();
}else
{
lgSize = fiFile.length();
int i = 1;
while(true)
{
if(lgSize > Long.valueOf(1 * 1024 * 1024))
{
strLogName = strFolder + Com_Para.zxyPath + "zxyong_" + Sub
+ Com_Fun.DateTimeStr("yyyyMMdd") + "_"
+ String.valueOf(i) + ".log";
fiFile = new File(strLogName);
if(!fiFile.exists())
{
fiFile.createNewFile();
sw = new FileWriter(strLogName,true);
sw.write("*********"
+ Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss")
+ "*********\r\n");
sw.write(strContent.toString());
sw.close();
break;
}else
{
lgSize = fiFile.length();
}
}else
{
sw = new FileWriter(strLogName,true);
sw.write("*********"
+ Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss")
+ "*********\r\n");
sw.write(strContent.toString());
sw.close();
break;
}
i++;
}
}
}
// 按日保存日誌文件
private void SaveFileDay() throws IOException
{
String strLogName = "";
if(this.getStrTFileName() == "")
strLogName = strFolder + Com_Para.zxyPath + "zxyong_"
+ Com_Fun.DateTimeStr("yyyyMMdd") + "_0.log";
else
strLogName = strFolder + Com_Para.zxyPath + this.getStrTFileName()
+ ".log";
fiFile = new File(strLogName);
long lgSize = 0;
FileWriter sw = null;
if(!fiFile.exists())
{
fiFile.createNewFile();
sw = new FileWriter(strLogName,true);
sw.write("*********" + Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss")
+ "*********\r\n");
sw.write(strContent + "\r\n");
sw.close();
}else
{
lgSize = fiFile.length();
int i = 1;
while(true)
{
if(lgSize > Long.valueOf(1 * 1024 * 1024))
{
if(this.getStrTFileName() == "")
strLogName = strFolder + Com_Para.zxyPath + "zxyong_"
+ Com_Fun.DateTimeStr("yyyyMMdd") + "_"
+ String.valueOf(i) + ".log";
else
strLogName = strFolder + Com_Para.zxyPath
+ this.getStrTFileName()
+ Com_Fun.DateTimeStr("yyyyMMdd") + "_"
+ String.valueOf(i) + ".log";
fiFile = new File(strLogName);
if(!fiFile.exists())
{
fiFile.createNewFile();
sw = new FileWriter(strLogName,true);
sw.write("*********"
+ Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss")
+ "*********\r\n");
sw.write(strContent.toString());
sw.close();
break;
}else
{
lgSize = fiFile.length();
}
}else
{
sw = new FileWriter(strLogName,true);
sw.write("*********"
+ Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss")
+ "*********\r\n");
sw.write(strContent.toString());
sw.close();
break;
}
i++;
}
}
}
// 判斷文件夾是否存在,不存在則添加文件夾
private void HadForder()
{
File file = new File(this.getStrFolder());
if(!file.exists() && !file.isDirectory())
{
file.mkdir();
}
}
}
com.zxy.main.webAppMain類:主程序入口main函數
package com.zxy.main;
import java.util.Timer;
import com.zxy.common.Com_Para;
import com.zxy.common.Init_Page;
import com.zxy.task.SelfTimeTask;
import com.zxy.tcp.ServerThreadHttp;
public class webAppMain
{
public static void main(String[] args) throws Exception
{
System.out.println("webAppMain開始");
try
{
//加載全局變量信息
Init_Page.Init_Load();
}
catch(Exception es)
{
es.printStackTrace();
}
//是否啓用http協議接口
if(Com_Para.bThread == true)
{
//開啓http web服務
ServerThreadHttp athttp = new ServerThreadHttp("","");
athttp.start();
}
/****執行定時器 每30秒執行一次***/
Timer time2 = new Timer();
SelfTimeTask sthreadT = new SelfTimeTask();
time2.scheduleAtFixedRate(sthreadT,10000,30000);
System.out.println("webAppMain結束");
}
}
com.zxy.task.SelfTimeTask類:定時器任務類
package com.zxy.task;
import com.zxy.common.Com_Para;
public class SelfTimeTask extends java.util.TimerTask
{
@Override
public void run()
{
RunTask();
}
private void RunTask()
{
//根據bTimeFlag標籤判斷任務是否執行中,防止定時器重複執行任務
if(!Com_Para.bTimeFlag)
{
Com_Para.bTimeFlag = true;
try
{
/* 編寫需要定時執行的任務 */
}
catch(Exception ee)
{
}
Com_Para.bTimeFlag = false;
}
}
}
com.zxy.tcp.Request類:加載數據request
com.zxy.tcp.Responst類
package com.zxy.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import com.zxy.common.Com_Para;
public class Request
{
public String strIP = "";
// 輸入流
private InputStream input;
// get提交url數據
private StringBuilder uri = new StringBuilder();
// post提交數據
private String[] post_str = null;
public Request(InputStream inputStream)
{
this.input = inputStream;
}
public InputStream getInput()
{
return input;
}
public void setInput(InputStream input)
{
this.input = input;
}
public StringBuilder getUri()
{
return uri;
}
public void setUri(StringBuilder uri)
{
this.uri = uri;
}
public String[] getPost_str()
{
if(post_str == null)
post_str = new String[0];
return post_str;
}
public void setPost_str(String post_str[])
{
this.post_str = post_str;
}
// 從套接字中讀取字符信息
public void parse() throws UnsupportedEncodingException
{
StringBuffer request = new StringBuffer(20480);
int i = -1;
try
{
/** 一次性讀取 **/
byte[] Bytes = new byte[20480];
i = this.input.read(Bytes,0,Bytes.length);
if(i != -1)
{
byte[] bytem = new byte[i];
for(int j = 0;j < i;j++)
{
bytem[j] = Bytes[j];
}
request.append(new String(bytem,Com_Para.U_CODE));
}
this.uri = parseUri(new StringBuilder(request.toString()));
String[] strCheck = PostData(request.toString());
if(strCheck[0] != ""
&& Integer.valueOf(strCheck[0].split(":")[1].trim()) == strCheck[1].getBytes(Com_Para.U_CODE).length)
{
post_str = strCheck[1].split("&");
if(!strCheck[1].equals(""))
{
this.uri.append("&" + strCheck[1]);
}
}else if(strCheck[0] != "" && strCheck[1] == ""
&& Integer.valueOf(strCheck[0].split(":")[1].trim()) > 0)
{
strCheck[1] = "";
InputStreamReader reader = new InputStreamReader(this.input,Com_Para.U_CODE);
char[] cr = new char[20480];
int in = reader.read(cr,0,cr.length);
for(int j = 0;j < in;j++)
{
request.append(cr[j]);
strCheck[1] += cr[j];
}
System.out.println("post內容:" + strCheck[1]);
post_str = strCheck[1].split("&");
if(!strCheck[1].equals(""))
{
this.uri.append("&" + strCheck[1]);
}
}
}
catch(IOException e)
{
System.out.println("sock內容異常:" + e.getMessage());
}
}
@SuppressWarnings("unused")
private StringBuilder readLine(InputStream is, int contentLe) throws IOException
{
StringBuffer request = new StringBuffer(2048);
byte[] readByte =
{ -1 };
int total = 0;
if(contentLe != 0)
{
do
{
readByte[0] = (byte) is.read();
if(readByte[0] != -1)
{
request.append(new String(readByte,Com_Para.U_CODE));
total++;
}
}
while(total < contentLe && readByte[0] != -1);// 消息體讀還未讀完
}else
{
String strTemStr = "";
do
{
readByte[0] = (byte) is.read();
if(readByte[0] == -1 && strTemStr.equals(""))
return new StringBuilder("\r\n");
else if(readByte[0] != -1)
strTemStr += new String(readByte,Com_Para.U_CODE);
}
while(readByte[0] != 10 && readByte[0] != -1);
request.append(strTemStr);
}
return new StringBuilder(request.toString());
}
private String[] PostData(String requestString) throws UnsupportedEncodingException
{
String[] strResult =
{ "", "" };
if(requestString.indexOf(Com_Para.Inf_Name) != -1
|| requestString.indexOf(Com_Para.web_Name[0]) != -1
|| requestString.indexOf(Com_Para.web_Name[1]) != -1)
{
String[] strTem = requestString.split("\r\n");
if(strTem[0].split(" ").length > 1
&& (strTem[0].split(" ")[0].equals("POST") || strTem[0].split(" ")[0].equals("OPTIONS")))
{
int Content_Length = -1;
String strEnd = requestString.substring(requestString.length() - 4,requestString.length());
if(!strEnd.equals("\r\n\r\n"))
{
strResult[1] = strTem[strTem.length - 1];
}
for(String strVal: strTem)
{
strVal = java.net.URLDecoder.decode(strVal,Com_Para.U_CODE);
if(strVal.indexOf("post_param: ") == 0)
{
strResult[1] = strVal.substring(strVal.indexOf("post_param: ") + 12,strVal.length());
strResult[0] = "Content-Length:"
+ String.valueOf(strResult[1].length());// strTem[3];
break;
}
if(strVal.indexOf("Content-Length:") == 0)
{
Content_Length = Integer.valueOf(strVal.split(":")[1].trim());
strResult[0] = "Content-Length:"
+ String.valueOf(Content_Length);
}
if(Content_Length > 0
&& Content_Length == strResult[1].getBytes(Com_Para.U_CODE).length)
{
break;
}
}
}
}
return strResult;
}
// 截取請求的url
private StringBuilder parseUri(StringBuilder requestString) throws UnsupportedEncodingException
{
StringBuilder strResult = new StringBuilder();
if(requestString.indexOf("/favicon.ico") != -1)
{
strResult.append("favicon.ico");
return strResult;
}else if(requestString.toString().indexOf(Com_Para.Inf_Name) != -1)
{
for(String strTem: requestString.toString().split("\r\n"))
{
if(strTem.indexOf(Com_Para.Inf_Name) != -1)
{
if(strTem.split(" ")[1].indexOf("?") != -1)
strResult.append((strTem.split(" ")[1]).split("\\?")[1]);
else
strResult.append(strTem.split(" ")[1]);
break;
}
}
}else if(requestString.toString().indexOf(Com_Para.web_Name[0]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[1]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[2]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[3]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[4]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[5]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[6]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[7]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[8]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[9]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[10]) != -1
|| requestString.toString().indexOf(Com_Para.web_Name[11]) != -1)
{
for(String strTem: requestString.toString().split("\r\n"))
{
if(strTem.indexOf(Com_Para.web_Name[0]) != -1
|| strTem.indexOf(Com_Para.web_Name[1]) != -1
|| strTem.indexOf(Com_Para.web_Name[2]) != -1
|| strTem.indexOf(Com_Para.web_Name[3]) != -1
|| strTem.indexOf(Com_Para.web_Name[4]) != -1
|| strTem.indexOf(Com_Para.web_Name[5]) != -1
|| strTem.indexOf(Com_Para.web_Name[6]) != -1
|| strTem.indexOf(Com_Para.web_Name[7]) != -1
|| strTem.indexOf(Com_Para.web_Name[8]) != -1
|| strTem.indexOf(Com_Para.web_Name[9]) != -1
|| strTem.indexOf(Com_Para.web_Name[10]) != -1
|| strTem.indexOf(Com_Para.web_Name[11]) != -1)
{
String strT = strTem.split(" ")[1];
if(strT.indexOf("?") == -1)
strResult.append(java.net.URLDecoder.decode(strTem.split(" ")[1],Com_Para.U_CODE));
else
strResult.append(java.net.URLDecoder.decode(strT.substring(0,strT.indexOf("?")),Com_Para.U_CODE));
break;
}
}
}else if(requestString.toString().length() > 10)
strResult = requestString;
return strResult;
}
}
package com.zxy.tcp;
import java.io.File;
import java.io.OutputStream;
import com.zxy.common.Com_Para;
public class Response
{
//獲取web路徑
public static final String WEB_ROOT = Com_Para.ApplicationPath
+ File.separator
+ "web";
// 關閉的命令
@SuppressWarnings("unused")
private static final int BUFFER_SIZE = 2048;
private Request request;
private OutputStream output;
public Response(OutputStream output)
{
this.output = output;
}
public Request getRequest()
{
return request;
}
public void setRequest(Request request)
{
this.request = request;
}
public OutputStream getOutput()
{
return output;
}
public void setOutput(OutputStream output)
{
this.output = output;
}
public static int getBUFFER_SIZE()
{
return BUFFER_SIZE;
}
}
com.zxy.tcp.ServerThreadHttp類:多線程tcp通訊
package com.zxy.tcp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import com.zxy.common.Com_Para;
import com.zxy.log.UsAdmin_Log;
public class ServerHandlerHttp implements Runnable
{
public static final String WEB_ROOT = Com_Para.ApplicationPath
+ File.separator + "web";
private Socket mServSocket;
private String strIP = "0.0.0.0";
public ServerHandlerHttp(Socket clientSocket)
{
this.mServSocket = clientSocket;
}
// web內容加載
private void webPage_Rel(StringBuilder strUrl, String s_guid, String[] post_str, StringBuilder returnMessage, OutputStream output, String web_name_s) throws Exception
{
File file = new File(WEB_ROOT
+ Com_Para.zxyPath
+ strUrl.toString().substring(0,strUrl.toString().indexOf(web_name_s))
+ web_name_s);
FileInputStream fis = null;
InputStreamReader is = null;
BufferedReader br = null;
if(file.exists())
{
try
{
output.write(returnMessage.append("\r\n\r\n").toString().getBytes(Com_Para.U_CODE));
int BUFFER_SIZE = 0;
fis = new FileInputStream(file);
byte[] sbytes = new byte[100];
while((BUFFER_SIZE = fis.read(sbytes)) != -1)
{
output.write(sbytes,0,BUFFER_SIZE);
}
}
catch(Exception e)
{
}
finally
{
if(fis != null)
fis.close();
if(is != null)
is.close();
if(br != null)
br.close();
}
output.write("\r\n".getBytes());
output.flush();
output.close();
}else
{
StringBuilder errorMessage = new StringBuilder("HTTP/1.1 404 File Not Found\r\n"
+ "Content-Type: text/html\r\n"
+ "Content-Length: 230\r\n"
+ "\r\n" + "<h1>未找到正確頁面</h1>");
try
{
output.write(errorMessage.toString().getBytes(Com_Para.U_CODE));
output.write("\r\n".getBytes());
output.flush();
output.close();
}
catch(IOException e)
{
}
}
}
// 發送錯誤信息
private StringBuilder Send_Error(StringBuilder strUrl, String s_guid, String[] post_str, StringBuilder returnMessage) throws Exception
{
returnMessage.delete(0,returnMessage.length());
returnMessage.append("Error請求語法錯誤");
return returnMessage;
}
// 線程init
private void init()
{
/* 跟蹤當前socket連接數 */
Com_Para.socket_count++;
//跟蹤性能時可調試
//System.out.println("當前增加線程,總數:" + String.valueOf(Com_Para.socket_count));
InputStream input = null;
OutputStream output = null;
StringBuilder strGS = new StringBuilder("HTTP/1.1 200 OK\r\n"
+ "Content-Type: text/html\r\n"
+ "Access-Control-Allow-Methods: POST,GET\r\n"
+ "Access-Control-Allow-Origin: *\r\n"// + Com_Para.HttpUrl
+ "Connection: Keep-Alive");
try
{
strIP = this.mServSocket.getRemoteSocketAddress().toString();
strIP = strIP.substring(1,strIP.indexOf(":"));
input = this.mServSocket.getInputStream();
output = this.mServSocket.getOutputStream();
Request request = new Request(input);
request.strIP = strIP;
request.parse();
Response response = new Response(output);
response.setRequest(request);
StringBuilder strUrl = request.getUri();
String[] post_str = request.getPost_str();
System.out.println("接收到get數據內容:"+strUrl.toString());
for(String poststr : post_str)
{
System.out.println("接收到post數據內容:"+poststr);
}
/* 判斷request是否出現異常 */
StringBuilder returnMessage = new StringBuilder("HTTP/1.1 200 OK\r\n");
if(strUrl.indexOf(".html") != -1)
returnMessage.append("Content-Type: text/html\r\n");
else if(strUrl.indexOf(".js") != -1)
returnMessage.append("Content-Type: application/x-javascript\r\n");
else if(strUrl.indexOf(".css") != -1)
returnMessage.append("Content-Type: text/css\r\n");
else if(strUrl.indexOf(".jpg") != -1)
returnMessage.append("Content-Type: image/jpg\r\n");
else if(strUrl.indexOf(".gif") != -1)
returnMessage.append("Content-Type: image/jpg\r\n");
else if(strUrl.indexOf(".png") != -1)
returnMessage.append("Content-Type: mage/png\r\n");
else if(strUrl.indexOf(".svg") != -1)
returnMessage.append("Content-Type: text/svg+xml\r\n");
else if(strUrl.indexOf(".eot") != -1)
returnMessage.append("Content-Type: application/vnd.ms-fontobject\r\n");
else if(strUrl.indexOf(".ttf") != -1)
returnMessage.append("Content-Type: application/x-font-ttf\r\n");
else if(strUrl.indexOf(".woff") != -1)
returnMessage.append("Content-Type: application/x-font-woff\r\n");
else if(strUrl.indexOf(".woff2") != -1)
returnMessage.append("Content-Type: application/x-font-woff\r\n");
else if(strUrl.indexOf(".ico") != -1)
returnMessage.append("Content-Type: image/ico\r\n");
else
returnMessage.append("Content-Type: text/html\r\n");
returnMessage.append("Access-Control-Allow-Methods: POST,GET\r\n"
+ "Access-Control-Allow-Origin:*" + Com_Para.HttpUrl
+ "\r\n" + "Connection: Keep-Alive");
//默認爲-1
StringBuilder strResult = new StringBuilder("-1");
String s_guid = "";
// 通用接口,根據get到的url內容判斷是否加載web文件內容
if(strUrl.indexOf(Com_Para.web_Name[0]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[0]);
}else if(strUrl.indexOf(Com_Para.web_Name[1]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[1]);
}else if(strUrl.indexOf(Com_Para.web_Name[2]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[2]);
}else if(strUrl.indexOf(Com_Para.web_Name[3]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[3]);
}else if(strUrl.indexOf(Com_Para.web_Name[4]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[4]);
}else if(strUrl.indexOf(Com_Para.web_Name[5]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[5]);
}else if(strUrl.indexOf(Com_Para.web_Name[6]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[6]);
}else if(strUrl.indexOf(Com_Para.web_Name[7]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[7]);
}else if(strUrl.indexOf(Com_Para.web_Name[8]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[8]);
}else if(strUrl.indexOf(Com_Para.web_Name[9]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[9]);
}else if(strUrl.indexOf(Com_Para.web_Name[10]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[10]);
}else if(strUrl.indexOf(Com_Para.web_Name[11]) != -1)
{
webPage_Rel(strUrl,s_guid,post_str,returnMessage,output,Com_Para.web_Name[11]);
}
//假設請求數據接口name爲TA33001
else if(strUrl.indexOf("TA33001") != -1)
{
//此處編寫加載數據接口內容
/******************/
strResult.delete(0,strResult.length());
strResult.append("你的接口數據內容");
/******************/
}
// 其他信息
else if((!strUrl.toString().trim().equals(""))
&& (strUrl.toString().trim().indexOf("GET /favicon.ico HTTP/1.1") != -1))
{
strResult.delete(0,strResult.length());
strResult = Send_Error(strUrl,s_guid,post_str,returnMessage);
}
if(!strResult.toString().equals("-1"))
{
output.write((returnMessage.toString() + "\r\n\r\n"
+ strResult.toString() + "\r\n").getBytes(Com_Para.U_CODE));
output.flush();
output.close();
}
}
catch(Exception e)
{
UsAdmin_Log uL = new UsAdmin_Log(Com_Para.ApplicationPath,new StringBuilder("接收到錯誤請求[ServerHandlerHttp]\r\n"
+ e.getMessage()));
try
{
uL.WriteLog();
}
catch(IOException localIOException4)
{
}
try
{
output.write(strGS.append("\r\n\r\n").append(e.getMessage()).append("\r\n").toString().getBytes(Com_Para.U_CODE));
}
catch(IOException e1)
{
}
}
finally
{
try
{
if(input != null)
input.close();
if(output != null)
output.close();
if(this.mServSocket != null)
{
Com_Para.socket_count--;
//跟蹤性能時可調試
//System.out.println("當前減少線程,總數:"+ String.valueOf(Com_Para.socket_count));
}
}
catch(Exception ees)
{
}
}
//釋放資源
System.gc();
}
public void run()
{
try
{
init();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
com.zxy.tcp.ServerHandlerHttp類:webpage數據請求處理
package com.zxy.tcp;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.zxy.common.Com_Para;
import com.zxy.log.UsAdmin_Log;
public class ServerThreadHttp extends Thread
{
public ExecutorService executorService; // 線程
public ServerSocket accSocket; // 接收數據socket
private String strInput = "";
private String strNum = "";
public void setStrInput(String strInput)
{
this.strInput = strInput;
}
public String getStrNum()
{
return strNum;
}
public void setStrNum(String strNum)
{
this.strNum = strNum;
}
public ServerThreadHttp(String Input, String Num)
{
this.strNum = Num;
this.strInput = Input;
}
public String getStrInput()
{
return strInput;
}
/**以下代碼從網上copy,有興趣可以自行編寫異步通訊模式**/
public void run()
{
try
{
accSocket = new ServerSocket(Com_Para.port);
}
catch(IOException e)
{
UsAdmin_Log uL = new UsAdmin_Log(Com_Para.ApplicationPath,new StringBuilder(String.valueOf(Com_Para.port)
+ "端口已被佔用"));
try
{
uL.WriteLog();
}
catch(IOException e1)
{
}
}
// 創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閒線程,若無可回收,則新建線程。
executorService = Executors.newCachedThreadPool();
while(true)
{
Socket socket = null;
try
{
socket = accSocket.accept();
executorService.execute(new ServerHandlerHttp(socket));
}
catch(Exception e)
{
System.out.println("error executorService"
+ Thread.activeCount() + e.getMessage());
}
finally
{
}
try
{
Thread.sleep(10);
}
catch(InterruptedException e)
{
}
}
}
}