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);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值