Httpserver 例子

package httpserver;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;


public class HttpServer implements Runnable {

ServerSocket serverSocket;//服務器Socket

public static int PORT = 80;//標準HTTP端口

public String encoding = "UTF-8";

public HttpServer() {
try {
//serverSocket = new ServerSocket(PORT,10,InetAddress.getByName("127.0.0.1"));
serverSocket = new ServerSocket(PORT,10,InetAddress.getByName("127.0.0.1"));
//serverSocket = new ServerSocket(PORT);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
new Thread(this).start();
System.out.println("HTTP服務器正在運行,端口:" + PORT);
}

public void run() {
while (true) {
try {
Socket client = serverSocket.accept();//客戶機(這裏是 IE 等瀏覽器)已經連接到當前服務器
if (client != null) {
System.out.println("連接到服務器的用戶:" + client);
try {
// 第一階段: 打開輸入流
InputStream is = client.getInputStream();
// 讀取第一行, 請求地址
String line = readLine(is, 0);
//System.out.println("line==="+line);
String sql = line;
//System.out.println("sql==="+sql);
String returnInfo = null;
if (sql.startsWith("_")) {//查詢user
returnInfo = selectUser(sql.substring(1));
}else if(sql.startsWith("+")){//insert
//System.out.println("執行插入語句操作");
returnInfo = String.valueOf(insertObj(sql.substring(1)));
}else if(sql.startsWith("#")){
returnInfo = String.valueOf(selectStageId(sql.substring(1)));
}else{
returnInfo = selectObject(sql);
}
//打印請求行
//System.out.print("=====客戶端請求====="+line);
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
System.out.println("server=="+returnInfo);
out.println(returnInfo);
out.close();
closeSocket(client);
} catch (Exception e) {
System.out.println("HTTP服務器錯誤:" + e.getLocalizedMessage());
}
}
} catch (Exception e) {
System.out.println("HTTP服務器錯誤:" + e.getLocalizedMessage());
}
}
}

@SuppressWarnings("unchecked")
private String readLine(InputStream is, int contentLe) throws IOException {
ArrayList lineByteList = new ArrayList();
byte readByte;
int total = 0;
if (contentLe != 0) {
do {
readByte = (byte) is.read();
lineByteList.add(Byte.valueOf(readByte));
total++;
} while (total < contentLe);//消息體讀還未讀完
} else {
do {
readByte = (byte) is.read();
lineByteList.add(Byte.valueOf(readByte));
} while (readByte != 10);
}

byte[] tmpByteArr = new byte[lineByteList.size()];
for (int i = 0; i < lineByteList.size(); i++) {
tmpByteArr[i] = ((Byte) lineByteList.get(i)).byteValue();
}
lineByteList.clear();

String tmpStr = new String(tmpByteArr, encoding);
if (tmpStr.startsWith("Referer")) {//如果有Referer頭時,使用UTF-8編碼
tmpStr = new String(tmpByteArr, "UTF-8");
}
return tmpStr;
}

void closeSocket(Socket socket) {
try {
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
PORT = 80;
//PORT = 80;
new HttpServer();
}
public static String selectObject(String querySql){
String strInfo = null;
Connection conn = null;
PreparedStatement pstat = null;
ResultSet rs = null;
try {
conn = getConnection();
pstat = conn.prepareStatement(querySql);
rs = pstat.executeQuery();
while(rs.next()){
Long id = rs.getLong("ID");
String u_company = rs.getString("U_Company");
String u_name = rs.getString("U_Name");
String w_addTime = rs.getString("W_AddTime");
strInfo = id+"/"+u_company + "/" + u_name + "/" + w_addTime;
}
} catch (SQLException e) {
e.printStackTrace();
}
clossConnection(rs, null,pstat, conn);
return strInfo;
};
public static String selectUser(String querySql){
String strInfo = null;
Connection conn = null;
PreparedStatement pstat = null;
ResultSet rs = null;
try {
conn = getConnection();
pstat = conn.prepareStatement(querySql);
rs = pstat.executeQuery();
while(rs.next()){
Long id = rs.getLong("ID");
String u_company = rs.getString("U_Company");
String u_name = rs.getString("U_Name");
strInfo = id+"/"+u_company + "/" + u_name ;
}
} catch (SQLException e) {
e.printStackTrace();
}
clossConnection(rs, null,pstat, conn);
return strInfo;
};
public static int selectStageId(String querySql){
int id = 0;
Connection conn = null;
PreparedStatement pstat = null;
ResultSet rs = null;
try {
conn = getConnection();
pstat = conn.prepareStatement(querySql);
rs = pstat.executeQuery();
while(rs.next()){
id = rs.getInt("id");
}
} catch (SQLException e) {
e.printStackTrace();
}
clossConnection(rs, null,pstat, conn);
return id;
}
public static int insertObj(String insertSql){
int flag = 0;//0:插入失敗;1:成功
Connection conn = null;
Statement stat = null;
try {
conn = getConnection();
stat = conn.createStatement();
flag = stat.executeUpdate(insertSql);
} catch (SQLException e) {
e.printStackTrace();
}
clossConnection(null,stat,null, conn);
return flag;
}
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=CheckWebCenter","sa","speech");
conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=CheckWebCenter","sa","SARFT281");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void clossConnection(ResultSet rs,Statement stat,PreparedStatement pstmt,Connection conn){
if (rs!=null){try {rs.close();}catch(Exception e){}}
if (stat!=null){try {stat.close();}catch(Exception e){}}
if (pstmt!=null){try {pstmt.close();}catch(Exception e){}}
if (conn!=null){try {conn.close();}catch(Exception e){}}
}
}

客戶端:package httpserver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;

public class HttpServerClient {
private static String encoding = "GBK";

public String getMessage(String sql){
String returnInfo = null;
try {
Socket s = new Socket(InetAddress.getByName("127.0.0.1"),80);
//Socket s = new Socket(InetAddress.getByName("127.0.0.1"),80);
OutputStreamWriter osw = new OutputStreamWriter(s.getOutputStream());
StringBuffer sb = new StringBuffer();
//querySql = "select top 1 ROW_NUMBER() OVER(ORDER BY t.W_AddTime DESC) as rownum ,t.ID,t.W_AddTime,u.U_Company,u.U_Name from C_WebSiteJNJW t left join C_User u on t.W_UserID = u.ID where t.W_WGLink = 'http://www.zhuzhut.com/vod-play-id-31199-sid-0-pid-334.html'";
//System.out.println("client  sql=="+sql);
sb.append(sql);
//注,這是關鍵的關鍵,忘了這裏讓我搞了半個小時。這裏一定要一個回車換行,表示消息頭完,不然服務器會等待
sb.append("\r\n");
osw.write(sb.toString());
osw.flush();
//--輸出服務器傳回的消息的頭信息
InputStream is = s.getInputStream();
int contentLength = 0;//服務器發送回來的消息長度
//--輸消息的體
returnInfo = readLine(is, contentLength);
//System.out.print("回執信息2=="+returnInfo);
//關閉流
is.close();
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println("client===="+returnInfo);
return returnInfo;
}
@SuppressWarnings("unchecked")
private static String readLine(InputStream is, int contentLe) throws IOException {
ArrayList lineByteList = new ArrayList();
byte readByte;
int total = 0;
if (contentLe != 0) {
do {
readByte = (byte) is.read();
lineByteList.add(Byte.valueOf(readByte));
total++;
} while (total < contentLe);//消息體讀還未讀完
} else {
do {
readByte = (byte) is.read();
lineByteList.add(Byte.valueOf(readByte));
} while (readByte != 10);
}

byte[] tmpByteArr = new byte[lineByteList.size()];
for (int i = 0; i < lineByteList.size(); i++) {
tmpByteArr[i] = ((Byte) lineByteList.get(i)).byteValue();
}
lineByteList.clear();
//System.out.println(new String(tmpByteArr));
return new String(tmpByteArr, encoding);
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章