Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Now that we’ve got a client set up and a server for it to connect to, we need to

ID: 3672600 • Letter: N

Question

Now that we’ve got a client set up and a server for it to connect to, we need to send data back and forth. Finish the code for both classes to send numbers between the server and the client. Assume all variables and imports are properly set up. Be sure to finish the code for BOTH classes. If you have trouble, check the Oracle API. (30 points)

public class NewClient

{

    //Variables Created

   

    //Main Execution

    public static void main(String[] args)

    {

        //Catch a possible connectivity error

        try

        {

            //Connection set up – establish Input and Output Streams.

            //Note: This is only one possible way to send data.

            reader = new DataInputStream(socket.getInputStream());

            writer = new DataOutputStream(socket.getOutputStream());

           

            //Pseudocode: random number generated.

            int clientNumber = x;

            int serverNumber;

           

            //Send the random number to the server.

            //**WRITE YOUR CODE BELOW THIS LINE**

           

           

            //Receive the random number from the server.

            //**WRITE YOUR CODE BELOW THIS LINE**

           

            

            System.out.println(“Server’s number: “ + serverNumber);

        }

        catch (IOException ex)

        {

            //Inform the user of the error

            System.out.println(“Error connecting to server.”);

        }

    }

}

public class NewServer

{

    //Variables Created

   

    //Main Execution

    public static void main(String[] args)

    {

        //Catch a possible connectivity error

        try

        {

            //Connection set up – establish Input and Output Streams.

            //Note: This is only one possible way to send data.

            reader = new DataInputStream(clientSocket.getInputStream());

           writer = new DataOutputStream(clientSocket.getOutputStream());

           

            //Pseudocode: random number generated.

            int clientNumber;

            int serverNumber = x;

           

            //Receive the random number from the client.

            //**WRITE YOUR CODE BELOW THIS LINE**

           

           

            //Send the random number to the client.

            //**WRITE YOUR CODE BELOW THIS LINE**

           

           

            System.out.println(“Client’s number: “ + clientNumber);

        }

        catch (IOException ex)

        {

            //Inform the user of the error

            System.out.println(“Error connecting to server.”);

        }

    }

}

public class NewClient

{

    //Variables Created

   

    //Main Execution

    public static void main(String[] args)

    {

        //Catch a possible connectivity error

        try

        {

            //Connection set up – establish Input and Output Streams.

            //Note: This is only one possible way to send data.

            reader = new DataInputStream(socket.getInputStream());

            writer = new DataOutputStream(socket.getOutputStream());

           

            //Pseudocode: random number generated.

            int clientNumber = x;

            int serverNumber;

           

            //Send the random number to the server.

            //**WRITE YOUR CODE BELOW THIS LINE**

           

           

            //Receive the random number from the server.

            //**WRITE YOUR CODE BELOW THIS LINE**

           

            

            System.out.println(“Server’s number: “ + serverNumber);

        }

        catch (IOException ex)

        {

            //Inform the user of the error

            System.out.println(“Error connecting to server.”);

        }

    }

}

Explanation / Answer

myclient.java


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

class ClientThread implements Runnable
{
   private static Socket clientSocket = null;

   private static PrintStream outputstream = null;
   private static DataInputStream inputstream = null;
  
   private static BufferedReader inputLine = null;
   private static boolean flag = true;

   public static void main(String[] args)
   {
      
       //setting default port and host name
       String host = "localhost";
       int port = 8080;

       // command line arguments
       if(args.length < 2)
       {
           System.out.println("Default port has been set: " + port);
       }
       else
       {
           host = args[0];
           port = Integer.parseInt(args[1]);
       }

       /*
       * Now open a socket on host and port names set above
       */
       try
       {
           clientSocket = new Socket(host,port);

           inputstream = new DataInputStream(clientSocket.getInputStream());
           outputstream = new PrintStream(clientSocket.getOutputStream());
          
           //inputLine reads lines from cmd
           inputLine = new BufferedReader(new InputStreamReader(System.in)); //default sized input buffer (can define size as well)

       } catch(IOException e)
       {
           System.err.println("IO exception");
           //e.printStackTrace();
       }

       if(clientSocket != null && inputstream != null && outputstream != null)
       {
           try
           {
               //creating thread to read from server
               ClientThread newclient = new ClientThread();
               Thread t = new Thread(newclient);
               t.start();   //executes a call to run () method

               while (flag == true)
               {
                   outputstream.println(inputLine.readLine().trim());
               }

               // Close the output stream, input stream and socket in reverse order that they were created
               outputstream.close();
               inputstream.close();
               clientSocket.close();

           } catch(IOException e)
           {
               e.printStackTrace();
           }
       }
   }

   public void run()
   {
       String response;
       try
       {
           while((response = inputstream.readLine()) != null)
           {
               if(response.indexOf("offline") != -1)
                   break;
               System.out.println(response);
           }
           flag = false;      
       } catch(IOException e)
       {
           flag = false;
           System.err.println("IOException: " + e);
       }
   }
}

Server.java

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

public class Server {

   private ServerSocket serverSocket;
   /* HashTable created for storing the entries for clients */
   Map clientList = new HashMap();

   public Server(int serverPort) throws IOException {
      waitForConnection(serverPort);
   }

   public void waitForConnection(int serverPort) throws IOException {
      serverSocket = new ServerSocket(serverPort);       //Attempts to create a server socket bound to the specified port
      serverSocket.setSoTimeout(1000000);                //sets the server waiting time-out value

      while (true) {                                     //loop to accept connections as they come

         /* Set up incoming connection in new socket */
         Socket s = serverSocket.accept();      //waits for an incoming client
         //System.out.println( getRemoteSocketAddress() + " is now online!" );
         System.out.println( s + " is now connected." );
       
         DataOutputStream out = new DataOutputStream( s.getOutputStream() );
       
         clientList.put(s, out);

         /* create a new thread to handle the new client */
         new ServerThread(this,s);
      }
   }

   void sendToAll( String message ) {

      Iterator it = clientList.entrySet().iterator();

      /* Sending messages iteratively to all clients */
      while (it.hasNext()) {
         Map.Entry entry = (Map.Entry) it.next();
         DataOutputStream out = (DataOutputStream)entry.getValue();
         try {
            out.writeUTF( message );
         } catch( IOException e ) {
            System.out.println(e);
         }
      }
   }

   void removeConnection( Socket s ) {

      System.out.println( "Removing connection to " + s );
      // Remove it from clientList Hashmap
      clientList.remove(s);

      try {
         s.close();
      } catch( IOException e ) {
         System.out.println( "Error closing connection for " + s );
         e.printStackTrace();
      }
   }

   public static void main(String [] args) throws Exception {
         int serverPort = Integer.parseInt(args[0]);
         new Server(serverPort);
   }

}

ServerThread.java
import java.net.*;
import java.io.*;
import java.util.*;

public class ServerThread extends Thread {
   private Server server;
   private Socket socket;

   public ServerThread(Server server, Socket socket) {
      this.server = server;
      this.socket = socket;
      /* Starts the new thread of this object by calling the run method */
      start();
   }

   /* overriding the run method of the thread class */
   public void run() {
      try {
         int flag=0;
         String uname;
         DataInputStream in = new DataInputStream(socket.getInputStream());

         while (true) {
            if (flag == 0) {                          //first reply from client(the username)
               uname = (in.readUTF());
               flag++;
            }
            else {
               String message = (in.readUTF());
               server.sendToAll(message);
            }
         }
      } catch(SocketTimeoutException s) {
         System.out.println("Connection timed out!");
      } catch(IOException e) {
         e.printStackTrace();
      } finally {
         server.removeConnection(socket);
      }
   }
}

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

class ClientThread implements Runnable
{
    private static Socket clientSocket = null;

   private static PrintStream outputstream = null;
   private static DataInputStream inputstream = null;
  
   private static BufferedReader inputLine = null;
   private static boolean flag = true;

   public static void main(String[] args)
   {
      
       //setting default port and host name
       String host = "localhost";
       int port = 8080;

       // command line arguments
       if(args.length < 2)
       {
           System.out.println("Default port has been set: " + port);
       }
       else
       {
           host = args[0];
           port = Integer.parseInt(args[1]);
       }

       /*
       * Now open a socket on host and port names set above
       */
       try
       {
           clientSocket = new Socket(host,port);

           inputstream = new DataInputStream(clientSocket.getInputStream());
           outputstream = new PrintStream(clientSocket.getOutputStream());
          
           //inputLine reads lines from cmd
           inputLine = new BufferedReader(new InputStreamReader(System.in)); //default sized input buffer (can define size as well)

       } catch(IOException e)
       {
           System.err.println("IO exception");
           //e.printStackTrace();
       }

       if(clientSocket != null && inputstream != null && outputstream != null)
       {
           try
           {
               //creating thread to read from server
               ClientThread newclient = new ClientThread();
               Thread t = new Thread(newclient);
               t.start();   //executes a call to run () method

               while (flag == true)
               {
                   outputstream.println(inputLine.readLine().trim());
               }

               // Close the output stream, input stream and socket in reverse order that they were created
               outputstream.close();
               inputstream.close();
               clientSocket.close();

           } catch(IOException e)
           {
               e.printStackTrace();
           }
       }
   }

   public void run()
   {
       String response;
       try
       {
           while((response = inputstream.readLine()) != null)
           {
               if(response.indexOf("offline") != -1)
                   break;
               System.out.println(response);
           }
           flag = false;      
       } catch(IOException e)
       {
           flag = false;
           System.err.println("IOException: " + e);
       }
   }
}

copyclient.java
import java.io.*;
import java.net.*;
import java.util.*;

class ClientThread implements Runnable
{
   private static Socket clientSocket = null;

   private static DataOutputStream outputstream = null;
   private static DataInputStream inputstream = null;

   private static BufferedReader reader = null;
  
   private static boolean flag = true;
   static String inputLine = null;
   static String userName = "Me";

   public static void main(String[] args)
   {
      
       //setting default port and host name
       String host = "localhost";
       int port = 8080;

       // command line arguments 172.16.8.55
       if(args.length < 2)
       {
           System.out.println("Default port has been set: " + port);
       }
       else
       {
           host = args[0];
           port = Integer.parseInt(args[1]);
       }

       //Now open a socket on host and port names set above
       try
       {
           clientSocket = new Socket(host,port);

           inputstream = new DataInputStream(clientSocket.getInputStream());
           outputstream = new DataOutputStream(clientSocket.getOutputStream());

           reader = new BufferedReader(new InputStreamReader(System.in));
          
       } catch(IOException e)
       {
           System.err.println("IO exception");
       }

       if(clientSocket != null && inputstream != null && outputstream != null)
       {
           //String response;
           try
           {
               //creating thread to read from server
               ClientThread newclient = new ClientThread();
               Thread t = new Thread(newclient);
               t.start();   //executes a call to run () method

               //Scanner scan = new Scanner( System.in );
               System.out.print("Choose your NickName: ");
               userName = reader.readLine().trim();
               outputstream.writeUTF(userName + ": ");
               System.out.println("***Welcome " + userName + ", You are now online!***");
               System.out.println("***Type 'quit' to go offline; Type 'list' to see who's online***");

               while (flag)
               {
                   System.out.print(userName+": ");
                   inputLine = reader.readLine().trim();
                   if(inputLine != null && !inputLine.isEmpty())
                   {
                       if(inputLine.equals("quit"))
                       {                      
                           outputstream.writeUTF("***" + userName + " is now offline!***");
                           flag = false;
                           break;
                       }
                       outputstream.writeUTF(userName+": "+inputLine);  
                   }  
               }

               // Close the output stream, input stream and socket in reverse order that they were created
               outputstream.close();
               inputstream.close();
               clientSocket.close();

           } catch(IOException e)
           {
               e.printStackTrace();
           }
       }
   }

   public void run()
   {
       try
       {
          
           while(true)
           {              
               System.out.println(inputstream.readUTF());
           }
                  
       } catch(IOException e)
       {
           flag = false;
           System.err.println("***You are now offline!***");
       }
   }
}

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

class ClientThread implements Runnable
{
   private static Socket clientSocket = null;

   private static PrintStream outputstream = null;
   private static DataInputStream inputstream = null;
  
   private static BufferedReader inputLine = null;
   private static boolean flag = true;

   public static void main(String[] args)
   {
      
       //setting default port and host name
       String host = "localhost";
       int port = 8080;

       // command line arguments
       if(args.length < 2)
       {
           System.out.println("Default port has been set: " + port);
       }
       else
       {
           host = args[0];
           port = Integer.parseInt(args[1]);
       }

       /*
       * Now open a socket on host and port names set above
       */
       try
       {
           clientSocket = new Socket(host,port);

           inputstream = new DataInputStream(clientSocket.getInputStream());
           outputstream = new PrintStream(clientSocket.getOutputStream());
          
           //inputLine reads lines from cmd
           inputLine = new BufferedReader(new InputStreamReader(System.in)); //default sized input buffer (can define size as well)

       } catch(IOException e)
       {
           System.err.println("IO exception");
           //e.printStackTrace();
       }

       if(clientSocket != null && inputstream != null && outputstream != null)
       {
           try
           {
               //creating thread to read from server
               ClientThread newclient = new ClientThread();
               Thread t = new Thread(newclient);
               t.start();   //executes a call to run () method

               while (flag == true)
               {
                   outputstream.println(inputLine.readLine().trim());
               }

               // Close the output stream, input stream and socket in reverse order that they were created
               outputstream.close();
               inputstream.close();
               clientSocket.close();

           } catch(IOException e)
           {
               e.printStackTrace();
           }
       }
   }

   public void run()
   {
       String response;
       try
       {
           while((response = inputstream.readLine()) != null)
           {
               if(response.indexOf("offline") != -1)
                   break;
               System.out.println(response);
           }
           flag = false;      
       } catch(IOException e)
       {
           flag = false;
           System.err.println("IOException: " + e);
       }
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote