简单的多线程套接字服务器不起作用(套接字已关闭)

时间:2019-01-14 01:14:42

标签: multithreading sockets

我有一个非常简单的多线程服务器。

当我的客户呼叫服务器时,服务器给出以下异常: java.net.SocketException:套接字已关闭 但是我的代码没有关闭套接字。

第一个代码段是我的客户。第二和第三代码段定义了服务器及其处理请求的方式。我有另一个单线程客户端服务器,它工作正常。 有人可以帮忙看看吗?

public class SocketClient {
public static void main(String[] args) {
    String hostname = "127.0.0.1";
    int port = 900;

    try{
        Socket socket = new Socket(hostname, port);
        OutputStream output = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(output, true);
        writer.println("GET /");
        writer.println();
        writer.flush();

        InputStream input = socket.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(input));

        String line;

        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (UnknownHostException ex) {
            System.out.println("Server not found: " + ex.getMessage());
    } catch (IOException ex) {
            System.out.println("I/O error: " + ex.getMessage());
    }
}

}

public class SimpleHTTPServer {
public static void main(String[] args) throws Exception {
    //create a network socket which can accept connection on certain TCP port
    //create Server which can accept requests
    final ServerSocket server = new ServerSocket(900);
    System.out.println("Listening for connection on port 900...");
    while(true) {
        try (Socket socket = server.accept()) { //creates socket when new request is received
            System.out.println("received request");
            RequestHandler rh = new RequestHandler(socket); //RequestHandler implements runnable interface, pass this object to create Thread
            Thread thread = new Thread(rh);
            thread.start(); //begins run() method defined in rh
        }
    }
}

}

public class RequestHandler implements Runnable {
private Socket socket;
public RequestHandler(Socket socket) {
    this.socket = socket;
}
@Override
public void run() {
    try {
        System.out.println("calling handleRequest");
        handleRequest();
    } catch (Exception e) {
        System.err.println(e);
        try {
            socket.close();
        } catch (IOException e1) {
            System.err.println("Error Closing socket connection");
            System.exit(0);
        }
    }
}
private void handleRequest() throws Exception {
    System.out.println("handleRequest called");
    Date today = new Date();
    String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + today;
    System.out.println("1st" + httpResponse);
    socket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
    System.out.println("2nd" + httpResponse);
    System.out.println("got a new request");
}

}

1 个答案:

答案 0 :(得分:0)

我将服务器更改为以下服务器,并且可以正常工作-

static

}