IterativeServer.java 1.67 KB
Newer Older
Michele Fiori's avatar
Michele Fiori committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
package sums;

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

class IterativeServer {
    public static void main(String argv[]) throws Exception {
        int portService;
        String numbersString;
        String[] numbersArray;
        float sum;

        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Please, insert the service port number:");
        portService = Integer.parseInt(inFromUser.readLine());

        // create a "listening socket" on the specified port
        ServerSocket welcomeSocket = new ServerSocket(portService);

        while(true) {
			/*	accept is a blocking call
				once a new connection arrived, it creates
				a new "established socket"	*/
            Socket connectionSocket = welcomeSocket.accept();
            System.out.print("Client address: " + connectionSocket.getInetAddress() + ", port: " + connectionSocket.getPort());

            // input stream from the socket initialization
            BufferedReader inFromClient =
                    new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

            // output stream to the socket initialization
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

            // read a line (that terminates with \n) from the client
            numbersString = inFromClient.readLine();
            numbersArray = numbersString.split(" ");

            sum = Float.parseFloat(numbersArray[0]) + Float.parseFloat(numbersArray[1]);

            // send the response to the client
            outToClient.writeBytes(sum + "\n");
        }
    }
}