Demo
2016-03-21 17:54
288 查看
ClientThread
package Note.Jetty;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Date;
public class ClientThread implements Runnable{
private Socket socket;
private float requestDelay = (float)0.7;
private BufferedReader bufferedReader;
private PrintStream printStream;
public ClientThread(Socket socket){
this.socket = socket;
}
public void run() {
// TODO Auto-generated method stub
try {
this.bufferedReader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.printStream = new PrintStream(this.socket.getOutputStream());
String requestString = this.getValidRequest();
if( !requestString.equals("") ) {
System.out.print("当前虚拟机最大可用内存为:");
System.out.println(Runtime.getRuntime().maxMemory()/1024/1024+"M");
System.out.print("当前,虚拟机已占用内存:");
System.out.println(Runtime.getRuntime().totalMemory()/1024/1024+"M");
this.printStream.println("HTTP/1.1 200 OK");
Date now = new Date();
this.printStream.println("Data:" + now);
this.printStream.println("Server: JHServer");
this.printStream.println("Access-Control-Allow-Origin:*");
this.printStream.println("Content-Type: text/html; charset=UTF-8");
this.printStream.println();
String content = "Vincent";
//IndeMatchInfo imi = new IndeMatchInfo(22,22,2,2,22,(double)0.0,"S7-200");
//content = imi.getHTML();
//imi.clear();
//imi = null;
System.out.print("当前虚拟机最大可用内存为:");
System.out.println(Runtime.getRuntime().maxMemory()/1024/1024+"M");
System.out.print("当前,虚拟机已占用内存:");
System.out.println(Runtime.getRuntime().totalMemory()/1024/1024+"M");
this.printStream.println(content);
content = "";
this.printStream.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressWarnings("finally")
//getValidRequest() 验证WEB的请求消息是否是伪HTTP协议。
//若不符合,或者请求时不发送任何消息头(例如通过telent访问)
private String getValidRequest() {
float second = (float) 0.0;
boolean isGo = true;
String request = null;
try {
while (!this.bufferedReader.ready()) {
second += 0.01;
if (second > this.requestDelay) {
System.out.println("One Client Delayed " + this.socket);
isGo = false;
break;
}
Thread.sleep(10);
}
if (isGo == true) {
request = this.bufferedReader.readLine();
if( request.contains("GET /") && request.contains(" HTTP/") ) {
request = request.substring(request.indexOf("/"),request.indexOf(" HTTP/"));
System.out.println("Client Request Info: " + request);
} else {
isGo = false;
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} finally {
if(isGo == true) {
return request;
} else {
return "";
}
}
}
private void close() {
try {
if (this.bufferedReader != null) {
this.bufferedReader.close();
this.bufferedReader = null;
}
if (this.printStream != null) {
this.printStream.close();
this.printStream = null;
}
if (this.socket != null) {
this.socket.close();
this.socket = null;
}
System.out.println("One Client Disconnected...");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server
package Note.Jetty;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static int PORT = 1723;
public static String charset = "UTF-8";
private ServerSocket ServerSocket;
private Socket clientSocket;
public static void main(String[] argStrings) {
new Server();
}
public Server() {
// TODO Auto-generated constructor stub
try {
this.ServerSocket = new ServerSocket(this.PORT);
System.out.println("Server is listening on Port: "+ this.PORT);
boolean isGo = true;
while (isGo) {
this.clientSocket = this.ServerSocket.accept();
System.out.println("One Client Connected." + this.clientSocket);
ClientThread clientThread = new ClientThread(this.clientSocket);
Thread thread = new Thread(clientThread);
thread.start();
System.out.println("One Client Thread Already Started.");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if (this.ServerSocket != null) {
this.ServerSocket.close();
this.ServerSocket = null;
}
if (this.clientSocket != null) {
this.clientSocket.close();
this.clientSocket = null;
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
package Note.WebCan;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
public static final String WEB_ROOT_STRING = System.getProperty("user.dir") + File.separator + "webroot";
private static final String SHUTDOWN_COMMAND_STRING = "/SHUTDOWN";
private boolean shutdown = false;
public static void main(String[] rags) {
HttpServer httpServer = new HttpServer();
httpServer.await();
}
public void await()
{
ServerSocket serverSocket =null;
int port = 1723;
try {
serverSocket = new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
while (!shutdown) {
Socket socket = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
socket = serverSocket.accept();
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
Request request = new Request(inputStream);
request.parse();
System.out.println("___");
//Create Response object
Response response = new Response(outputStream);
response.setRequest(request);
response.sendStaticResource();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println("ERROR");
continue;
}
}
}
}
package Note.WebCan;
import java.io.IOException;
import java.io.InputStream;
public class Request {
private InputStream inputStream;
private String URI;
public Request(InputStream input)
{
this.inputStream = input;
}
public void parse(){
StringBuffer request = new StringBuffer();
int i;
byte[] buffer = new byte[2048];
try {
i = inputStream.read(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
i = -1;
}
for (int j = 0; j < i; j++) {
request.append(buffer[j]);
}
System.out.println(request.toString());
URI = parseUri(request.toString());
}
public String parseUri(String requestString)
{
int index1;
int index2;
index1 = requestString.indexOf(" ");
if (index1 != -1) {
index2 = requestString.indexOf(" ",index1 + 1);
if (index2 > index1) {
return requestString.substring(index1 + 1,index2);
}
}
return null;
}
public String getUri() {
return this.URI;
}
}
package Note.WebCan;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream outputStream;
public Response(OutputStream output) {
this.outputStream = output;
}
public void setRequest(Request Request) {
this.request = Request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fileInputStream = null;
try {
File file = new File("C:\\Users\\pl59770.NAM\\WorkSpaceForDemo\\Jetty\\src\\webroot");
if (file.exists()) {
System.err.println("File Exists");
fileInputStream = new FileInputStream(file);
int ch = fileInputStream.read(bytes, 0, BUFFER_SIZE);
while (ch != -1) {
outputStream.write(bytes, 0, BUFFER_SIZE);
ch = fileInputStream.read(bytes, 0, BUFFER_SIZE);
}
} else {
String errorMessageString = "HTTP/1.1 404 File Not Found\r\n"
+ "Content-Type:text/html\r\n"
+ "Content-Length:23\r\n" + "\r\n"
+ "<h1>File Not Found</h1>";
outputStream.write(errorMessageString.getBytes());
}
} catch (Exception e) {
// TODO: handle exception
//System.err.println(e.toString());
e.printStackTrace();
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
}
}
}
package Note.Jetty;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Date;
public class ClientThread implements Runnable{
private Socket socket;
private float requestDelay = (float)0.7;
private BufferedReader bufferedReader;
private PrintStream printStream;
public ClientThread(Socket socket){
this.socket = socket;
}
public void run() {
// TODO Auto-generated method stub
try {
this.bufferedReader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.printStream = new PrintStream(this.socket.getOutputStream());
String requestString = this.getValidRequest();
if( !requestString.equals("") ) {
System.out.print("当前虚拟机最大可用内存为:");
System.out.println(Runtime.getRuntime().maxMemory()/1024/1024+"M");
System.out.print("当前,虚拟机已占用内存:");
System.out.println(Runtime.getRuntime().totalMemory()/1024/1024+"M");
this.printStream.println("HTTP/1.1 200 OK");
Date now = new Date();
this.printStream.println("Data:" + now);
this.printStream.println("Server: JHServer");
this.printStream.println("Access-Control-Allow-Origin:*");
this.printStream.println("Content-Type: text/html; charset=UTF-8");
this.printStream.println();
String content = "Vincent";
//IndeMatchInfo imi = new IndeMatchInfo(22,22,2,2,22,(double)0.0,"S7-200");
//content = imi.getHTML();
//imi.clear();
//imi = null;
System.out.print("当前虚拟机最大可用内存为:");
System.out.println(Runtime.getRuntime().maxMemory()/1024/1024+"M");
System.out.print("当前,虚拟机已占用内存:");
System.out.println(Runtime.getRuntime().totalMemory()/1024/1024+"M");
this.printStream.println(content);
content = "";
this.printStream.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressWarnings("finally")
//getValidRequest() 验证WEB的请求消息是否是伪HTTP协议。
//若不符合,或者请求时不发送任何消息头(例如通过telent访问)
private String getValidRequest() {
float second = (float) 0.0;
boolean isGo = true;
String request = null;
try {
while (!this.bufferedReader.ready()) {
second += 0.01;
if (second > this.requestDelay) {
System.out.println("One Client Delayed " + this.socket);
isGo = false;
break;
}
Thread.sleep(10);
}
if (isGo == true) {
request = this.bufferedReader.readLine();
if( request.contains("GET /") && request.contains(" HTTP/") ) {
request = request.substring(request.indexOf("/"),request.indexOf(" HTTP/"));
System.out.println("Client Request Info: " + request);
} else {
isGo = false;
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} finally {
if(isGo == true) {
return request;
} else {
return "";
}
}
}
private void close() {
try {
if (this.bufferedReader != null) {
this.bufferedReader.close();
this.bufferedReader = null;
}
if (this.printStream != null) {
this.printStream.close();
this.printStream = null;
}
if (this.socket != null) {
this.socket.close();
this.socket = null;
}
System.out.println("One Client Disconnected...");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server
package Note.Jetty;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static int PORT = 1723;
public static String charset = "UTF-8";
private ServerSocket ServerSocket;
private Socket clientSocket;
public static void main(String[] argStrings) {
new Server();
}
public Server() {
// TODO Auto-generated constructor stub
try {
this.ServerSocket = new ServerSocket(this.PORT);
System.out.println("Server is listening on Port: "+ this.PORT);
boolean isGo = true;
while (isGo) {
this.clientSocket = this.ServerSocket.accept();
System.out.println("One Client Connected." + this.clientSocket);
ClientThread clientThread = new ClientThread(this.clientSocket);
Thread thread = new Thread(clientThread);
thread.start();
System.out.println("One Client Thread Already Started.");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if (this.ServerSocket != null) {
this.ServerSocket.close();
this.ServerSocket = null;
}
if (this.clientSocket != null) {
this.clientSocket.close();
this.clientSocket = null;
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
package Note.WebCan;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
public static final String WEB_ROOT_STRING = System.getProperty("user.dir") + File.separator + "webroot";
private static final String SHUTDOWN_COMMAND_STRING = "/SHUTDOWN";
private boolean shutdown = false;
public static void main(String[] rags) {
HttpServer httpServer = new HttpServer();
httpServer.await();
}
public void await()
{
ServerSocket serverSocket =null;
int port = 1723;
try {
serverSocket = new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
while (!shutdown) {
Socket socket = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
socket = serverSocket.accept();
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
Request request = new Request(inputStream);
request.parse();
System.out.println("___");
//Create Response object
Response response = new Response(outputStream);
response.setRequest(request);
response.sendStaticResource();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println("ERROR");
continue;
}
}
}
}
package Note.WebCan;
import java.io.IOException;
import java.io.InputStream;
public class Request {
private InputStream inputStream;
private String URI;
public Request(InputStream input)
{
this.inputStream = input;
}
public void parse(){
StringBuffer request = new StringBuffer();
int i;
byte[] buffer = new byte[2048];
try {
i = inputStream.read(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
i = -1;
}
for (int j = 0; j < i; j++) {
request.append(buffer[j]);
}
System.out.println(request.toString());
URI = parseUri(request.toString());
}
public String parseUri(String requestString)
{
int index1;
int index2;
index1 = requestString.indexOf(" ");
if (index1 != -1) {
index2 = requestString.indexOf(" ",index1 + 1);
if (index2 > index1) {
return requestString.substring(index1 + 1,index2);
}
}
return null;
}
public String getUri() {
return this.URI;
}
}
package Note.WebCan;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream outputStream;
public Response(OutputStream output) {
this.outputStream = output;
}
public void setRequest(Request Request) {
this.request = Request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fileInputStream = null;
try {
File file = new File("C:\\Users\\pl59770.NAM\\WorkSpaceForDemo\\Jetty\\src\\webroot");
if (file.exists()) {
System.err.println("File Exists");
fileInputStream = new FileInputStream(file);
int ch = fileInputStream.read(bytes, 0, BUFFER_SIZE);
while (ch != -1) {
outputStream.write(bytes, 0, BUFFER_SIZE);
ch = fileInputStream.read(bytes, 0, BUFFER_SIZE);
}
} else {
String errorMessageString = "HTTP/1.1 404 File Not Found\r\n"
+ "Content-Type:text/html\r\n"
+ "Content-Length:23\r\n" + "\r\n"
+ "<h1>File Not Found</h1>";
outputStream.write(errorMessageString.getBytes());
}
} catch (Exception e) {
// TODO: handle exception
//System.err.println(e.toString());
e.printStackTrace();
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
}
}
}
相关文章推荐
- 如何在Windows Server 2008中安装IIS
- 匹配所有图片
- xml01 验证
- Java多线程系列--“JUC锁”07之 LockSupport
- 用java实现数的深度遍历和广度遍历
- ElasticSearch 和packetBeat 的使用
- 第一部分:浅析 Linux 初始化 init 系统:sysvinit
- MySQL数据库学习--JDBC的ResultSet接口(查询操作)、PreparedStatement接口重构增删改查
- PHP删除文件(夹)
- hibernate 一对多(one-to-many)双向关联
- 随便转
- java 字符串连接
- 关于COOKIE使用过程为NULL
- IIS7配置PHP图解
- 文档操作:将pdf页面转换成UIImage
- 【项目管理】generatorConfig.xml配置信息详细
- iOS开发的经典博客和文章汇总
- hdu 1068 Girls and Boys 二分图匹配 最大独立集
- NSURLSession复用
- DelphiXE7中创建WebService(服务端+客户端)