TCPServer.java 1.13 KB
Newer Older
riccardo presotto's avatar
riccardo presotto committed
1 2 3 4 5 6 7 8 9 10
import java.io.*; 
import java.net.*; 

class TCPServer { 

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

11
		/* Create a "listening socket" on the specified port */
riccardo presotto's avatar
riccardo presotto committed
12 13 14 15
		ServerSocket welcomeSocket = new ServerSocket(6789); 

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

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

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

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

33
			/* Build the response */
riccardo presotto's avatar
riccardo presotto committed
34 35
			capitalizedSentence = clientSentence.toUpperCase() + '\n'; 

36
			/* Send the response to the client */
riccardo presotto's avatar
riccardo presotto committed
37 38 39 40 41 42 43
			outToClient.writeBytes(capitalizedSentence);

			connectionSocket.close();

		}
	}
}