Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 持续连接不工作,在每个请求时打开新连接_Java_Sockets_Http_Server_Persistent Connection - Fatal编程技术网

Java 持续连接不工作,在每个请求时打开新连接

Java 持续连接不工作,在每个请求时打开新连接,java,sockets,http,server,persistent-connection,Java,Sockets,Http,Server,Persistent Connection,我试图用java实现一个持久的http服务器,这是套接字编程的新手,我不知道其中的复杂性。 但如果运行ThreadHandler类的函数,它将永远阻塞并保持等待,但同时,如果出现新请求,则会创建一个新连接,而不是使用前一个连接本身,而初始连接将保持等待请求。 请建议更正 这是我调用ThreadHandler进行线程处理的服务器代码 服务器代码 package httpServer; import java.io.BufferedReader; import java.io.DataOutput

我试图用java实现一个持久的http服务器,这是套接字编程的新手,我不知道其中的复杂性。 但如果运行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();
        }

    }
}

我没有通读整个代码,但是我没有看到您向客户机发回除内容长度之外的任何响应头。持久连接要求客户端发送一个头连接:保持活动状态,服务器使用相同的头连接进行响应。您似乎没有发送此响应头,因此客户端可能认为不支持持久连接。