ServerThread.java 1.5 KB
Newer Older
Luca Arrotta's avatar
Luca Arrotta committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package multithread;

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

public class ServerThread extends Thread {
    private Socket connectionSocket = null;
    private BufferedReader inFromClient;
    private DataOutputStream outToClient;

    // the constructor argument is an established socket
    public ServerThread(Socket s) {
        connectionSocket = s;
        try {
15 16

            /* Initialize input stream from the socket */
Luca Arrotta's avatar
Luca Arrotta committed
17 18 19
            inFromClient =
                    new BufferedReader(
                            new InputStreamReader(connectionSocket.getInputStream()));
20 21

            /* Initialize output stream towards the socket */
Luca Arrotta's avatar
Luca Arrotta committed
22 23
            outToClient =
                    new DataOutputStream(connectionSocket.getOutputStream());
24

Luca Arrotta's avatar
Luca Arrotta committed
25 26 27 28 29 30 31 32 33
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        String clientSentence;
        String capitalizedSentence;
        try {
34
            /* Read a line (ending with '\n') from the client */
Luca Arrotta's avatar
Luca Arrotta committed
35
            clientSentence = inFromClient.readLine();
36 37 38 39 40

            /* simulate a processing time of 10 seconds*/
            //Thread.sleep(10000);

            /* Build the response */
Luca Arrotta's avatar
Luca Arrotta committed
41
            capitalizedSentence = clientSentence.toUpperCase() + '\n';
42 43

            /* Send the response to the client */
Luca Arrotta's avatar
Luca Arrotta committed
44
            outToClient.writeBytes(capitalizedSentence);
45 46

            /* Close the connection socket */
Luca Arrotta's avatar
Luca Arrotta committed
47 48 49 50 51 52
            connectionSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}