IterativeServer.java 1.5 KB
Newer Older
Luca Arrotta's avatar
Luca Arrotta committed
1 2 3 4 5 6 7 8 9 10
package iterative;

import java.io.*;
import java.net.*;

class IterativeServer {
    public static void main(String argv[]) throws Exception {
        String clientSentence;
        String capitalizedSentence;

Michele Fiori's avatar
Michele Fiori committed
11
        /* Create a "listening socket" on the specified port */
Luca Arrotta's avatar
Luca Arrotta committed
12 13 14
        ServerSocket welcomeSocket = new ServerSocket(6789);

        while(true) {
Michele Fiori's avatar
Michele Fiori committed
15 16 17 18
            /*
             * Call to accept function (blocking call).
             * When a new connection arrives a new "established socket" is created
             */
Luca Arrotta's avatar
Luca Arrotta committed
19 20
            Socket connectionSocket = welcomeSocket.accept();

Michele Fiori's avatar
Michele Fiori committed
21
            /* Initialize input stream from the socket */
Luca Arrotta's avatar
Luca Arrotta committed
22 23 24 25
            BufferedReader inFromClient =
                    new BufferedReader(
                            new InputStreamReader(connectionSocket.getInputStream()));

Michele Fiori's avatar
Michele Fiori committed
26
            /* Initialize output stream towards the socket */
Luca Arrotta's avatar
Luca Arrotta committed
27 28 29
            DataOutputStream outToClient =
                    new DataOutputStream(connectionSocket.getOutputStream());

Michele Fiori's avatar
Michele Fiori committed
30
            /* Read a line (ending with '\n') from the client */
Luca Arrotta's avatar
Luca Arrotta committed
31 32
            clientSentence = inFromClient.readLine();

Michele Fiori's avatar
Michele Fiori committed
33
            /* simulate a processing time of 10 seconds*/
Luca Arrotta's avatar
Luca Arrotta committed
34 35
            //Thread.sleep(10000);

Michele Fiori's avatar
Michele Fiori committed
36
            /* Build the response */
Luca Arrotta's avatar
Luca Arrotta committed
37 38
            capitalizedSentence = clientSentence.toUpperCase() + '\n';

Michele Fiori's avatar
Michele Fiori committed
39
            /* Send the response to the client */
Luca Arrotta's avatar
Luca Arrotta committed
40
            outToClient.writeBytes(capitalizedSentence);
Michele Fiori's avatar
Michele Fiori committed
41 42 43

            /* Close the connection socket */
            connectionSocket.close();
Luca Arrotta's avatar
Luca Arrotta committed
44 45 46
        }
    }
}