Server.java
上传用户:kyckim
上传日期:2007-12-11
资源大小:332k
文件大小:18k
- package Pihatonttu;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.ProtocolException;
- import java.net.SocketTimeoutException;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.net.URL;
- import java.util.Calendar;
- import java.util.Enumeration;
- import java.util.Hashtable;
- import java.util.TooManyListenersException;
- import javax.comm.CommPortIdentifier;
- import javax.comm.NoSuchPortException;
- import javax.comm.PortInUseException;
- import javax.comm.SerialPort;
- import javax.comm.SerialPortEvent;
- import javax.comm.SerialPortEventListener;
- import javax.comm.UnsupportedCommOperationException;
- public class Server implements Runnable, SerialPortEventListener {
-
- private SerialPort comPort;
-
- private Calendar cal = null;
- private int year = 0;
- private String month = null;
- private int day_of_month = 0;
- private int hour = 0;
- private int minute = 0;
- private int second = 0;
-
- private String accessTime = null;
-
- private DataInputStream comReader;
- private DataOutputStream comWriter;
-
- private HttpURLConnection hc = null;
- private Socket socket = null;
- private DataInputStream reader;
- private DataOutputStream writer;
-
- private String requestMethod = null;
- private String requestURI = null;
- private String requestProtocol = null;
- private String requestHost = null;
- private int requestPort = 80;
- private Hashtable<String, String> requestHeaderField = new Hashtable<String, String>();
- private byte[] postData = null;
-
- private String responseProtocol = null;
- private String responseCode = null;
- private String responseMessage = null;
- private int byteTranfered = 0;
-
- private String host = null;
- private int port = 80;
-
- Server(String com, String proxy){
- CommPortIdentifier portID = null;
- try{
- portID = CommPortIdentifier.getPortIdentifier(com);
- }catch(NoSuchPortException e){
- Pihatonttu.PihatonttuMain.showErrorDialog("Cannnot find COM port.");
- System.exit(1);
- }
-
- try{
- comPort = (SerialPort)portID.open("Pihatonttu", 5000);
- }catch(PortInUseException e){
- Pihatonttu.PihatonttuMain.showErrorDialog("COM port is in use.");
- System.exit(1);
- }
-
- try {
- comPort.setSerialPortParams(460800, //9600?115200?230400?460800?921600?
- SerialPort.DATABITS_8,
- SerialPort.STOPBITS_1,
- SerialPort.PARITY_NONE);
- comPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
- } catch (UnsupportedCommOperationException e){
- Pihatonttu.PihatonttuMain.showErrorDialog("Cannnot configure COM port.");
- System.exit(1);
- }
-
- try {
- comPort.addEventListener(this);
- } catch(TooManyListenersException ex) {
- Pihatonttu.PihatonttuMain.showErrorDialog("COM port error.");
- System.exit(1);
- }
-
- comPort.notifyOnDataAvailable(true);
-
- if(!proxy.equals("null")) {
- int delimitPos = proxy.indexOf(':');
- host = proxy.substring(0, delimitPos);
- port = Integer.valueOf(proxy.substring(delimitPos + 1)).intValue();
- }
- }
-
- private void closeCOM(){
- try{
- if(comReader != null){
- comReader.close();
- comReader = null;
- }
- } catch(IOException e) {
- Pihatonttu.PihatonttuMain.showErrorDialog("Cannnot close input/output stream.");
- }
- try{
- if(comWriter != null){
- comWriter.close();
- comWriter = null;
- }
- } catch(IOException e) {
- Pihatonttu.PihatonttuMain.showErrorDialog("Cannnot close input/output stream.");
- }
- }
-
- private void closeHttp() {
- try{
- if(reader != null){
- reader.close();
- reader = null;
- }
- } catch(IOException e) {
- Pihatonttu.PihatonttuMain.showErrorDialog("Cannnot close input/output stream.");
- }
- try{
- if(writer != null){
- writer.close();
- writer = null;
- }
- } catch(IOException e) {
- Pihatonttu.PihatonttuMain.showErrorDialog("Cannnot close input/output stream.");
- }
- if(hc != null){
- hc.disconnect();
- hc = null;
- }
- }
-
- private void closeCOMPort(){
- if(comPort != null) {
- comPort.close();
- comPort = null;
- }
- }
-
- public void exitServer() {
- closeCOM();
- closeHttp();
- closeCOMPort();
- }
-
- public void serialEvent(SerialPortEvent event) throws MalformedURLException, ProtocolException {
- switch(event.getEventType()) {
- case SerialPortEvent.BI:
- case SerialPortEvent.OE:
- case SerialPortEvent.FE:
- case SerialPortEvent.PE:
- case SerialPortEvent.CD:
- case SerialPortEvent.CTS:
- case SerialPortEvent.DSR:
- case SerialPortEvent.RI:
- case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
- break;
- case SerialPortEvent.DATA_AVAILABLE:
-
- try {
- Pihatonttu.PihatonttuMain.togleIcon(true);
-
- comReader = new DataInputStream(comPort.getInputStream());
- comWriter = new DataOutputStream(comPort.getOutputStream());
-
- requestMethod = "";
- requestURI = "";
- requestProtocol = "";
- requestHeaderField.clear();
- requestHost = "";
- requestPort = 80;
- readRequestHeader();
-
- if(!requestMethod.equals("")) {
- // loadPage();
- accessTime = getAccessTime();
- Pihatonttu.PihatonttuMain.logFrame.addElement("localhost - - [" + getAccessTime()+ "] "" +
- requestMethod + " " + requestURI + " " + requestProtocol + """);
- // if(!requestProtocol.equals("RTSP/1.0")) {
- sendRequest();
-
- responseProtocol = "";
- responseCode = "";
- responseMessage = "";
- byteTranfered = 0;
-
- readResponseHeader();
- Pihatonttu.PihatonttuMain.logFrame.addElementFraction("localhost - - [" + accessTime + "] "" +
- requestMethod + " " + requestURI + " " + requestProtocol + "" " + responseCode);
-
- forwardResponse();
- if(responseCode.startsWith("30")) {
- Pihatonttu.PihatonttuMain.logFrame.addElementFraction("localhost - - [" + accessTime + "] "" +
- requestMethod + " " + requestURI + " " + requestProtocol + "" " + responseCode + " -");
- } else {
- Pihatonttu.PihatonttuMain.logFrame.addElementFraction("localhost - - [" + accessTime + "] "" +
- requestMethod + " " + requestURI + " " + requestProtocol + "" " + responseCode + " " + byteTranfered);
- }
- // } else {
- // sendStreamingRequest();
- // readStreamingResponse();
- // }
- }
- } catch(UnknownHostException e){
- returnUnknownHostException(comWriter);
- } catch(SocketTimeoutException e){
- returnUnknownHostException(comWriter);
- } catch (IOException e){
- if(e.getMessage().indexOf("unknown protocol") != -1) returnUnknownProtocolException(comWriter);
- else returnInternalServerException(comWriter);
- } finally {
- closeCOM();
- closeHttp();
- Pihatonttu.PihatonttuMain.togleIcon(false);
- }
- break;
- }
- }
-
- public void start(){
- Thread thread = new Thread(this);
- thread.start();
- }
-
- public void run(){
- String buffer = null;
- System.out.flush();
- }
-
- private void readRequestHeader() throws IOException {
- StringBuffer sb = new StringBuffer();
- int c;
- int line = 0;
- while((c = comReader.read()) != -1) {
- if((char)c == 'r') {
- if(sb.length() == 0) {
- break;
- } else {
- processRequestHeader(sb.toString(), line);
- sb.delete(0, sb.length());
- line++;
- }
- } else if((char)c == 'n') {
- } else {
- sb.append((char)c);
- }
- }
- sb = null;
- if(requestMethod.equals("POST")) {
- int dummy = comReader.read();
- if(requestHeaderField.get("content-length") != null) {
- int contentLength = Integer.valueOf((String)requestHeaderField.get("content-length")).intValue();
- postData = new byte[contentLength];
- comReader.read(postData, 0, contentLength);
- }
- }
- }
-
- private void processRequestHeader(String str, int line) throws IOException {
- str = str.trim();
-
- if(line == 0){
- int delimitPos = str.indexOf(' ');
- requestMethod = (str.substring(0, delimitPos)).trim();
- str = (str.substring(delimitPos + 1)).trim();
- delimitPos = str.indexOf(' ');
- requestURI = (str.substring(0, delimitPos)).trim();
- requestProtocol = (str.substring(delimitPos + 1)).trim();
- } else {
- int delimitPos = str.indexOf(':');
- String key = ((str.substring(0, delimitPos)).trim()).toLowerCase();
- String value = (str.substring(delimitPos + 1)).trim();
- if(key.equals("host")) {
- delimitPos = value.indexOf(':');
- if(delimitPos == -1) {
- requestHost = value;
- } else {
- requestHost = value.substring(0, delimitPos);
- requestPort = Integer.valueOf(value.substring(delimitPos + 1)).intValue();
- }
- }
- requestHeaderField.put(key, value);
- }
- }
-
- private void sendRequest() throws MalformedURLException, ProtocolException, IOException {
- URL url;
- if(host != null) {
- url = new URL("http", host, port, requestURI);
- } else {
- url = new URL(requestURI);
- }
- hc = (HttpURLConnection)url.openConnection();
- hc.setConnectTimeout(30 * 1000);
- hc.setReadTimeout(30 * 1000);
- hc.setRequestMethod(requestMethod);
- Enumeration e = requestHeaderField.keys();
- String key;
- String value;
- while (e.hasMoreElements()){
- key = (String)e.nextElement();
- value = (String)requestHeaderField.get(key);
- hc.setRequestProperty(key, value);
- // Pihatonttu.PihatonttuMain.logFrame.addElement(key +": " + value);
- }
- if(requestMethod.equals("POST")) {
- hc.setDoOutput(true);
- hc.connect();
- writer = new DataOutputStream(hc.getOutputStream());
- writer.write(postData);
- writer.flush();
- postData = null;
- } else {
- hc.connect();
- }
- }
-
- private void readResponseHeader() throws IOException {
- reader = new DataInputStream(hc.getInputStream());
- responseProtocol = "HTTP/1.1";
- responseCode = Integer.toString(hc.getResponseCode());
- responseMessage = hc.getResponseMessage();
- comWriter.write((responseProtocol + " " + responseCode + " " + responseMessage + "rn").getBytes());
-
- String key;
- for(int i = 1; ((key = hc.getHeaderFieldKey(i)) != null); i++){
- if(!key.equalsIgnoreCase("Transfer-Encoding")) {
- comWriter.write((key + ": " + hc.getHeaderField(i) +"rn").getBytes());
- // Pihatonttu.PihatonttuMain.logFrame.addElement(key + ": " + hc.getHeaderField(i));
- }
- }
- comWriter.write("rn".getBytes());
- }
-
- private void forwardResponse() throws IOException {
- int contentLength = (int)hc.getContentLength();
- if(contentLength > 0) {
- int temp = 0;
- int read = 0 ;
- byte[] buf = new byte[2048];
- while ((read < contentLength) && (temp != -1)) {
- temp = reader.read(buf, 0, 2048);
- if(temp != -1) {
- comWriter.write(buf, 0, temp);
- read += temp;
- byteTranfered += temp;
- Pihatonttu.PihatonttuMain.logFrame.addElementFraction("localhost - - [" + accessTime + "] "" +
- requestMethod + " " + requestURI + " " + requestProtocol + "" " + responseCode + " " + byteTranfered);
- }
- }
- buf = null;
- } else {
- byte[] buf = new byte[2048];
- int len = -1;
- while(true) {
- if((len = reader.read(buf, 0, 2048)) == -1) {
- break;
- } else {
- comWriter.write(buf, 0, len);
- byteTranfered += len;
- Pihatonttu.PihatonttuMain.logFrame.addElementFraction("localhost - - [" + accessTime + "] "" +
- requestMethod + " " + requestURI + " " + requestProtocol + "" " + responseCode + " " + byteTranfered);
- }
- }
- buf = null;
- }
- comWriter.flush();
- }
-
- private void sendStreamingRequest() throws IOException{
- int delimitPos = requestURI.lastIndexOf(':');
- if(delimitPos == -1) {
- requestHost = requestURI;
- requestPort = 554;
- } else {
- requestHost = requestURI.substring(7, delimitPos);
- requestPort = Integer.valueOf(requestURI.substring(delimitPos + 1)).intValue();
- }
-
- socket = new Socket(requestHost, requestPort);
- writer = new DataOutputStream(socket.getOutputStream());
- writer.write((requestMethod + " " + requestURI + " " + requestProtocol + "rn").getBytes());
- Enumeration e = requestHeaderField.keys();
- String key;
- String value;
- while (e.hasMoreElements()){
- key = (String)e.nextElement();
- value = (String)requestHeaderField.get(key);
- if(!key.equals("connection") && !key.equals("host")) {
- writer.write((key + ": " + value + "rn").getBytes());
- }
- }
- writer.write("rn".getBytes());
- writer.flush();
- }
-
- private void readStreamingResponse() throws IOException{
- reader = new DataInputStream(socket.getInputStream());
-
- StringBuffer sb = new StringBuffer();
- int c;
- int line = 0;
- while((c = readbuffer(reader, 10)) != -1) {
- if((char)c == 'r') {
- if(sb.length() == 0) {
- break;
- } else {
- // Pihatonttu.PihatonttuMain.logFrame.addElement(sb.toString());
- comWriter.write((sb.toString() + "rn").getBytes() );
- sb.delete(0, sb.length());
- line++;
- }
- } else if((char)c == 'n') {
- } else {
- sb.append((char)c);
- }
- }
- sb = null;
- comWriter.write("rn".getBytes());
- comWriter.flush();
- }
-
- private void returnUnknownHostException(DataOutputStream output) {
- try {
- output.write("HTTP/1.1 504 Gateway Timeoutrn".getBytes());
- output.write("Content-Type: text/htmlrnrn".getBytes());
- output.write("<html>".getBytes());
- output.write("<head><title>Problem loading page</title></head>".getBytes());
- output.write("<body>".getBytes());
- output.write("<h1>Server not found</h1>".getBytes());
- output.write(("<p>Pihatonttu Proxy can't find the server at "+ requestHost + ".</p>").getBytes());
- output.write("</body>".getBytes());
- output.write("</html>".getBytes());
- output.flush();
- } catch(IOException e) {
- Pihatonttu.PihatonttuMain.showErrorDialog("Bluetooth connnection is not available.");
- } finally {
- responseProtocol = "HTTP/1.1";
- responseCode = "504";
- responseMessage = "Gateway Timeout";
- byteTranfered = 0;
- Pihatonttu.PihatonttuMain.logFrame.addElementFraction("localhost - - [" + accessTime + "] "" +
- requestMethod + " " + requestURI + " " + requestProtocol + "" " + responseCode + " " + byteTranfered);
- }
- }
-
- private void returnInternalServerException(DataOutputStream output) {
- try {
- if(byteTranfered == 0) {
- output.write("HTTP/1.1 500 Internal Server Errorrn".getBytes());
- output.write("Content-Type: text/htmlrnrn".getBytes());
- output.write("<html>".getBytes());
- output.write("<head><title>Problem loading page</title></head>".getBytes());
- output.write("<body>".getBytes());
- output.write("<h1>500 Internal Server Error</h1>".getBytes());
- output.write(("<p>Pihatonttu Proxy encountered an internal error.</p>").getBytes());
- output.write("</body>".getBytes());
- output.write("</html>".getBytes());
- output.flush();
- }
- } catch(IOException e) {
- Pihatonttu.PihatonttuMain.showErrorDialog("Bluetooth connnection is not available.");
- } finally {
- responseProtocol = "HTTP/1.1";
- responseCode = "500";
- responseMessage = "Internal Server Error";
- // byteTranfered = 0;
- Pihatonttu.PihatonttuMain.logFrame.addElementFraction("localhost - - [" + accessTime + "] "" +
- requestMethod + " " + requestURI + " " + requestProtocol + "" " + responseCode + " " + byteTranfered);
- }
- }
-
- private void returnUnknownProtocolException(DataOutputStream output) {
- try {
- output.write("HTTP/1.1 501 Not Implementedrn".getBytes());
- output.write("Content-Type: text/htmlrnrn".getBytes());
- output.write("<html>".getBytes());
- output.write("<head><title>Problem loading page</title></head>".getBytes());
- output.write("<body>".getBytes());
- output.write("<h1>Protocol not supported</h1>".getBytes());
- output.write(("<p>Pihatonttu Proxy can't support requested protocol.</p>").getBytes());
- output.write("</body>".getBytes());
- output.write("</html>".getBytes());
- output.flush();
- } catch(IOException e) {
- Pihatonttu.PihatonttuMain.showErrorDialog("Bluetooth connnection is not available.");
- } finally {
- responseProtocol = "HTTP/1.1";
- responseCode = "501";
- responseMessage = "Not Implemented";
- byteTranfered = 0;
- Pihatonttu.PihatonttuMain.logFrame.addElementFraction("localhost - - [" + accessTime + "] "" +
- requestMethod + " " + requestURI + " " + requestProtocol + "" " + responseCode + " " + byteTranfered);
- }
- }
-
- private String getAccessTime() {
- cal = Calendar.getInstance();
- year = cal.get(Calendar.YEAR);
- switch(cal.get(Calendar.MONTH) + 1) {
- case 1: month = "Jan"; break;
- case 2: month = "Feb"; break;
- case 3: month = "Mar"; break;
- case 4: month = "Apr"; break;
- case 5: month = "May"; break;
- case 6: month = "Jun"; break;
- case 7: month = "Jul"; break;
- case 8: month = "Aug"; break;
- case 9: month = "Sep"; break;
- case 10: month = "Oct"; break;
- case 11: month = "Nov"; break;
- case 12: month = "Dec"; break;
- }
- day_of_month = cal.get(Calendar.DAY_OF_MONTH);
- hour = cal.get(Calendar.HOUR_OF_DAY);
- minute = cal.get(Calendar.MINUTE);
- second = cal.get(Calendar.SECOND);
- return formatNum(day_of_month) + "/" + month + "/" + year +
- ":" + formatNum(hour) + ":" + formatNum(minute) + ":" + formatNum(second) + " +0900";
- }
-
- private String formatNum(int num) {
- if(num < 10) return "0" + num;
- else return "" + num;
- }
-
- private static int readbuffer(DataInputStream stream, int reread) throws IOException {
- int c = -1;
- for(int i = 0; i < reread; i++) {
- if(stream.available() != 0) {
- c = stream.read();
- break;
- }
- try {
- Thread.sleep(100);
- } catch(InterruptedException e) {
- }
- }
- return c;
- }
-
- private static int readbuffer(DataInputStream stream, byte[] buf, int len, int reread) throws IOException {
- int c = -1;
- for(int i = 0; i < reread; i++) {
- if(stream.available() != 0) {
- c = stream.read(buf, 0, len);
- break;
- }
- try {
- Thread.sleep(100);
- } catch(InterruptedException e) {
- }
- }
- return c;
- }
- }