持久连接不起作用,在每个请求上打开新连接

时间:2014-11-03 22:27:25

标签: java sockets http server persistent-connection

我正在尝试在java中实现一个持久的http服务器,在socket编程中是新的,我不知道它们的复杂性。 但是运行ThreadHandler类的功能,它会永远停留并保持等待,但同时如果新请求到来,则建立新连接而不是使用先前的连接本身(当初始连接继续等待请求时)。 请建议更正 这是我的服务器代码,它调用ThreadHandler进行线程化。

服务器代码

package httpServer;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public class Server {
    static int countofconnections = 0;

    public static void main(String[] args) throws IOException {
        int port = 14998;

        ServerSocket socketServerSocket = new ServerSocket(port);

        while(true) {
            Socket socketClientSocket = socketServerSocket.accept();
            countofconnections++;


            //Runnable handler = new TinyHttpdSocketHandler(socket);
            ThreadHandler threadHandler = new ThreadHandler(socketClientSocket);
            Thread socketThread = new Thread(threadHandler, "Thread for " + socketClientSocket.toString());
            System.out.println(" connection count is now : " + countofconnections+ " ");
            socketThread.setDaemon(true);
            socketThread.start();               
        }

    }

}

ThreadHandler代码:

package httpServer;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketTimeoutException;
//import java.util.ArrayList;

public class ThreadHandler implements Runnable{
    Socket socketClientSocket;
    //ServerSocket socketServerSocket;

    ThreadHandler(Socket socketClientSocket){
        this.socketClientSocket = socketClientSocket;
        //this.socketServerSocket = socketServerSocket;
    }

    @Override
    public void run(){
        boolean alive = false;
        try {
            int count = 0;
            socketClientSocket.setSoTimeout(40000);
            BufferedReader inputFromClient = new BufferedReader(new InputStreamReader(socketClientSocket.getInputStream()));
            DataOutputStream outputToClient = new DataOutputStream(socketClientSocket.getOutputStream());


            String messegeFromClient = inputFromClient.readLine();
            System.out.println(messegeFromClient);

            while(messegeFromClient!=null) {
                String requestString = messegeFromClient;
                System.out.println("entering while loop");

                //String in = inputFromClient.readLine();

                while(messegeFromClient!=null && !messegeFromClient.equals("")) {
                    //System.out.printlnln(in);
                    messegeFromClient = inputFromClient.readLine();
                    //System.out.println(messegeFromClient);
                    if(messegeFromClient.startsWith("Connection:")) {
                        String[] connectionTimeString = messegeFromClient.split(" ");
                        if(connectionTimeString[1].equals("keep-alive")) {
                            alive = true;
                            //System.out.println("keep alive found");
                        }
                    }
                }
                count++;
                System.out.println(count);  
                //System.out.printlnln( messegeFromClient);
                String[] tokensStrings = requestString.split(" ");

                if(tokensStrings[0].equals("GET")) {
                    String requestedFilename = tokensStrings[1];
                    if(requestedFilename.startsWith("/")) {
                        requestedFilename = requestedFilename.substring(1);
                        if(requestedFilename.startsWith("~")) {
                            requestedFilename = "/home/suman/users/"+requestedFilename.substring(1);
                        }
                        else {
                            requestedFilename = "/home/suman/public_html/"+requestedFilename;
                        }
                        System.out.println(requestedFilename);
                    }
                    File filetosend = new File(requestedFilename);
                    int filesize = (int) filetosend.length();
                    FileInputStream fileStream = null;
                    boolean fileFound = true;
                    try {
                        fileStream = new FileInputStream(requestedFilename);                    
                    } catch (Exception e) {
                        fileFound = false;
                    }

                    if(fileFound) {
                        byte[] fileinByte =new byte[filesize];
                        fileStream.read(fileinByte);
                        outputToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n");
                        outputToClient.writeBytes("Content-Length: "+filesize+"\r\n\r\n");
                        outputToClient.write(fileinByte, 0, filesize);
                    }
                    else {
                        outputToClient.writeBytes("HTTP/1.0 404 Document NOT FOUND\r\n\r\n");
                        outputToClient.writeBytes("404 document not found");

                    }
                    outputToClient.flush();
                    if(alive) {
                        socketClientSocket.setKeepAlive(true);
                        socketClientSocket.setSoTimeout(100000);
                    }
                    else {
                        socketClientSocket.close();
                        System.out.println("closing socket");
                        break;
                    }
                    //socketClientSocket.setSoTimeout(5000);
                }
                System.out.println("waiting");
                messegeFromClient=inputFromClient.readLine();

                while( messegeFromClient == null ) {
                    //this code should be skipped when a new request is made since message from from client will no longer be null in that case
                    messegeFromClient=inputFromClient.readLine();
                }
                if(messegeFromClient==null) {
                    System.out.println("messege is null... I don't think it would be ever executed.");
                }
            }
            socketClientSocket.close();
            System.out.println("closing socket 2");
        } catch (  SocketTimeoutException e) {
            try {
                socketClientSocket.close();
                System.out.println("socket closed");
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } catch (IOException ie) {
            ie.printStackTrace();
        }

    }
}

0 个答案:

没有答案