packagecom.zhao.test;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.io.UnsupportedEncodingException;importjava.net.ServerSocket;importjava.net.Socket;importjava.net.URLDecoder;
public classSample_IIS {public static voidmain(String[] args) {
startServer(9000);
}private static void startServer(intport) {
System.out.println("======>startServer");try{
ServerSocket server= newServerSocket(port);
server.setSoTimeout(0);
Socket socket= null;while ((socket = server.accept()) != null) {
socket.setSoTimeout(2000);byte[] buffer = new byte[2048];
InputStream is=socket.getInputStream();int len =is.read(buffer);
getContent(buffer, len);
responseText(socket,"{\"cmd\":\"response\",\"inof\":\"success\"}");
socket.close();
}
}catch(IOException e) {
e.printStackTrace();
}
System.out.println("=====>");
}
private static voidresponseText(Socket pSocket, String content) {
StringBuffer buffer= newStringBuffer();//buffer.append("HTTP/1.1 200 OK\r\n");//buffer.append("Date: Tue, 14 Sep 1999 02:19:57 GMT\r\n");//buffer.append("Server: Apache/1.2.6\r\n");//buffer.append("Connection: close\r\n");//buffer.append("Content-Type: text/html\r\n");//buffer.append("\r\n");
buffer.append(content);try{
OutputStream os=pSocket.getOutputStream();
os.write(buffer.toString().getBytes());
os.flush();
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
private static String getContent(byte[] data, intlen) {
String result= "";
String content= new String(data, 0, len);
System.out.println("content: " +content);
String[] lines= content.split("\r\n");
String firstStr= lines[0];//判断是POST还是GET
String method = firstStr.split(" ")[0].toLowerCase();
System.out.println("method: " +method);if ("get".equals(method)) {//get
} else{//post
String line = lines[lines.length - 1];int index = line.indexOf("=");
result= line.substring(index + 1);try{
result= URLDecoder.decode(result, "gbk");
System.out.println("result: " +result);
}catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
}returnresult;
}
}