Commit de1071a1 authored by Michele Fiori's avatar Michele Fiori

Added comments on multi-thread

parent 2ae34c4c
...@@ -5,16 +5,22 @@ import java.net.*; ...@@ -5,16 +5,22 @@ import java.net.*;
class MultiServer { class MultiServer {
public static void main(String argv[]) throws Exception { public static void main(String argv[]) throws Exception {
/* Create a "listening socket" on the specified port */
ServerSocket welcomeSocket = new ServerSocket(6789); ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) { while(true) {
/*
* Call to accept function (blocking call).
* When a new connection arrives a new "established socket" is created
*/
Socket connectionSocket = welcomeSocket.accept(); Socket connectionSocket = welcomeSocket.accept();
// thread creation passing the established socket as arg /* Thread creation passing the established socket as argument */
ServerThread theThread = ServerThread theThread =
new ServerThread(connectionSocket); new ServerThread(connectionSocket);
// start of the thread /* Start the thread*/
theThread.start(); theThread.start();
} }
} }
......
...@@ -12,11 +12,16 @@ public class ServerThread extends Thread { ...@@ -12,11 +12,16 @@ public class ServerThread extends Thread {
public ServerThread(Socket s) { public ServerThread(Socket s) {
connectionSocket = s; connectionSocket = s;
try { try {
/* Initialize input stream from the socket */
inFromClient = inFromClient =
new BufferedReader( new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream())); new InputStreamReader(connectionSocket.getInputStream()));
/* Initialize output stream towards the socket */
outToClient = outToClient =
new DataOutputStream(connectionSocket.getOutputStream()); new DataOutputStream(connectionSocket.getOutputStream());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -26,9 +31,19 @@ public class ServerThread extends Thread { ...@@ -26,9 +31,19 @@ public class ServerThread extends Thread {
String clientSentence; String clientSentence;
String capitalizedSentence; String capitalizedSentence;
try { try {
/* Read a line (ending with '\n') from the client */
clientSentence = inFromClient.readLine(); clientSentence = inFromClient.readLine();
/* simulate a processing time of 10 seconds*/
//Thread.sleep(10000);
/* Build the response */
capitalizedSentence = clientSentence.toUpperCase() + '\n'; capitalizedSentence = clientSentence.toUpperCase() + '\n';
/* Send the response to the client */
outToClient.writeBytes(capitalizedSentence); outToClient.writeBytes(capitalizedSentence);
/* Close the connection socket */
connectionSocket.close(); connectionSocket.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment