samedi 2 avril 2016

Java Web Server: Single-threaded to Multi-threaded

I'm trying to create a multi-threaded server from this code:

public void start() throws IOException {
    // create a server socket
    ServerSocket serverSock = new ServerSocket(port);
    while (true) {
        // listen for a new connection on the server socket
        Socket conn = serverSock.accept();
        // get the input stream for receiving data from the client
        InputStream is = conn.getInputStream();
        // read the request message (but ignore it for now)
        try {
            Request req = Request.parse(is);
        } catch (MessageFormatException ex) {
        }
        // get the output stream for sending data to the client
        OutputStream os = conn.getOutputStream();
        // send a response
        Response msg = new Response(200);
        msg.write(os);
        os.write(" Hello, this is a message! \n".getBytes());
        // close the connection
        conn.close();
    }
}

I looked everywhere, found things like:

        new Thread(
        new WorkerRunnable(
        clientSocket, "Multithreaded Server")
        ).start();

But don't know how to use this. Could someone help please? Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire