We help IT Professionals succeed at work.
Get Started
Private
Troubleshooting Question

Multi client server Java program

Simon Leung
Simon Leung asked
on
36 Views
Last Modified: 2020-11-14
I code a multi client server java program to simulate a multiuser game program. Each client will take turn to input. If a client input "OK", all the clients will end normally except itself. I need to press Enter on this client in order to end it probably.

How can I modify the code such that this client (input "OK") will also end itself normally.

Thx 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {
public static void main(String args[]){

   int PlayerIdx = 0;

    Socket s=null;
    ServerSocket ss2=null;
    System.out.println("Server Listening......");
    try{
        ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined

    }
   catch(IOException e){
    e.printStackTrace();
    System.out.println("Server error");

    }

   GameWinner game = new GameWinner(false);
   
    while(true){
      try{
            s= ss2.accept();
            System.out.println("connection Established");
            ServerThread st=new ServerThread(s, PlayerIdx, game);  //start new thread for any incoming connection
            PlayerIdx++;
            st.start();

      }
      catch(Exception e){
            e.printStackTrace();
            System.out.println("Connection Error");

      }
    }

}

}

class GameWinner {
   boolean gameover;
   
   GameWinner(boolean bover)
   {
      this.gameover = bover;
   }
    
   boolean GetWinner(){
      return gameover;
   }
   
   void SetWinner(boolean bover){
      this.gameover = bover;
   }
}

class ServerThread extends Thread{  

    String line=null;
    BufferedReader  is = null;
    PrintWriter os=null;
    Socket s=null;
   
   int PlayerID;
   boolean neverPlay= true;
   GameWinner GamePlay;


    public ServerThread(Socket s, int p, GameWinner g){
        this.s=s;
      this.PlayerID=p;
      this.GamePlay=g;

    }

  public void run() {
    try{
        is= new BufferedReader(new InputStreamReader(s.getInputStream()));
        os=new PrintWriter(s.getOutputStream());

    }catch(IOException e){
        System.out.println("IO error in server thread");
    }
   try {
      
        line = "";
      
      while (line.compareTo("QUIT")!=0)  {
         
         //Sync Start
         synchronized(GamePlay) {
            if (neverPlay == false) {
               try {            
                  GamePlay.wait();  //wait for execution
                                    
               }catch(InterruptedException e){
                  e.printStackTrace();
               }
            }
            
            
            if (!GamePlay.GetWinner()) {
               try{
                  os.println(PlayerID + ", your turn now" );  // send message to client
                  os.flush();  //forces any buffered output bytes to be written out to their intended destination
            
                  line=is.readLine();         
                  System.out.println("Client Input :  " + line);

                  System.out.println("Game Start");
                  Thread.currentThread().sleep(5000);
                  System.out.println("Game End");
                }
               catch (InterruptedException itro){
                   System.out.println("sleep is interrupted");
               }   
            }
            
            if (line.compareTo("OK")==0) {
               line = "";
               GamePlay.SetWinner(true);
               System.out.println("Player " + PlayerID + "win the Game");
               os.println(PlayerID + ", you win the game." );  // send message to client
               os.flush();  //forces any buffered output bytes to be written out to their intended destination
            }else if (GamePlay.GetWinner()) {
               os.println("QUIT");   //send to the server
               os.flush();
            } 
            neverPlay=false;
            GamePlay.notify();  //notify execution
   
         }  //Sync End
               
        }   
    } catch (IOException e) {

        line=this.getName(); //reused String line for getting thread name
        System.out.println("IO Error/ Client "+line+" terminated abruptly");
    }
    catch(NullPointerException e){
        line=this.getName(); //reused String line for getting thread name
        System.out.println("Client "+line+" Closed");
    }
finally{    
    try{
        System.out.println("Connection Closing..");
        if (is!=null){
            is.close(); 
            System.out.println(" Socket Input Stream Closed");
        }

        if(os!=null){
            os.close();
            System.out.println("Socket Out Closed");
        }
        if (s!=null){
        s.close();
        System.out.println("Socket Closed");
        }
    }
    catch(IOException ie){
        System.out.println("Socket Close Error");
    }
    }//end finally
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class Client {

public static void main(String args[]) throws IOException{


    InetAddress address=InetAddress.getLocalHost();
    Socket s1=null;
   BufferedReader is=null;
   
    String line=null;
    BufferedReader br=null;
    
    PrintWriter os=null;   
   
   try {
        s1=new Socket(address, 4445);  
        
      //get server response, read from BufferedReader, console input
      br= new BufferedReader(new InputStreamReader(System.in));
      
      //get socket's input stream and open BufferedReader
        is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
        
      //get sockets output stream and opens a PrinterWriter
      //(send data through socket to server and write to PrinterWriter
      os= new PrintWriter(s1.getOutputStream()); 
    }
    catch (IOException e){
        e.printStackTrace();
        System.err.print("IO Exception");
    }
   System.out.println("Client Address : "+address);
    System.out.println("Enter Data to echo Server ( Enter QUIT to end):");

    String response=null;
    try{
         line = "";
        while(line.compareTo("QUIT")!=0){
         
         response=is.readLine();   //read a line of information from BufferedReader connected to the socket
            System.out.println("Server Response : "+response);
         
         if (response.compareTo("QUIT")!=0) {
            line=br.readLine();
            os.println(line);   //send to the server
            os.flush();
         } else {
            line = "QUIT";
            os.println("QUIT");   //send to the server
            os.flush();
         }
        }
    }
    catch(IOException e){
        e.printStackTrace();
    System.out.println("Socket read Error");
    }
    finally{

        br.close();os.close();br.close();s1.close();
                System.out.println("Connection Closed");

    }

}
}

Comment
Watch Question
CERTIFIED EXPERT
Distinguished Expert 2020
Commented:
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE