Part of Slepp's ProjectsPastebinTURLImagebinFilebin
Feedback -- English French German Japanese
Create Upload Newest Tools Donate
Sign In | Create Account

server
Friday, October 3rd, 2008 at 6:08:47am UTC 

  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.*;
  4. import java.awt.*;
  5. import javax.swing.*;
  6.  
  7.  
  8. public class server extends JFrame{
  9.   // Mapping of sockets to output streams
  10.   private Hashtable<Socket, DataOutputStream> hTable = new Hashtable<Socket, DataOutputStream>();
  11.  
  12.   JTextArea textArea = new JTextArea(12, 20);
  13.   boolean showOPG,singleGame;
  14.   Random rand = new Random();
  15.   int[] pattern = new int[4];
  16.   int[] guess = new int[4];
  17.   DataInputStream inputFromClient1;
  18.   DataOutputStream outputToClient1;
  19.   DataInputStream inputFromClient2;
  20.   DataOutputStream outputToClient2;
  21.   DataInputStream inputFromClient3;
  22.   DataOutputStream outputToClient3;
  23.   JScrollPane scrollPane = new JScrollPane(textArea); // Creates a scroll pane to hold text area
  24.  
  25.   ServerSocket serverSocket;
  26.   boolean winner = false;
  27.   int finalColorMatch, finalBothMatch;
  28.   int sessionID = 0, guessCounter = 0;
  29.   boolean multiGameOn = false;
  30.   int playerID;
  31.  
  32.   public static void main(String[] args) {
  33.     new server();
  34.   }
  35.  
  36.   public server() {
  37.     super("Server");
  38.     // creating the container needed by frame
  39.     Container container = getContentPane();
  40.     textArea.setEditable(false);
  41.     getContentPane().add(scrollPane, BorderLayout.CENTER); //Adds the scroll pane to the frame
  42.     container.add(textArea);
  43.     // designing the frame
  44.     setSize(500, 300);
  45.     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  46.     setVisible(true); // It is necessary to show the frame here
  47.  
  48.     // receive info from client
  49.     receiveClient();
  50.   }// end of constructor 
  51.  
  52.   // creating server socket and receive from client to get the specific info about the game
  53.   // such as single or multiple players, show feedback or not
  54.   public void receiveClient() {
  55.     try {
  56.       // Create a server socket
  57.       serverSocket = new ServerSocket(8000);
  58.       textArea.append("MastermindServer started at " + new Date() + "\n");
  59.       //create an array of threads
  60.       Thread[] threads = new Thread[6];
  61.  
  62.       while(true) {
  63.         multiGameOn = false;
  64.         winner = false;
  65.         // Listen for a connection request
  66.         Socket socket1 = serverSocket.accept();
  67. //        Socket socket2;
  68.         Socket socketMulti;
  69.         // create a session to keep track 
  70.         sessionID = 1;
  71.         // Create data input and output streams
  72.         inputFromClient1 = new DataInputStream(socket1.getInputStream());
  73.         outputToClient1 = new DataOutputStream(socket1.getOutputStream());
  74.        
  75.         // Sends session id to the client
  76.         // Notify that the player Player number
  77.         outputToClient1.writeInt(sessionID);//Multi(1)send sessionID
  78.         outputToClient1.flush();
  79.        
  80.         // Receive the game type from the client and send appropreate
  81.         // message to inform them they can start and handle a single
  82.         // thread or multiple accordingly
  83.         int singleOrMulti = inputFromClient1.readInt();
  84. System.out.println("singleOrMulti(2)" + singleOrMulti);
  85.         String message;
  86.         if(singleOrMulti == 1) {
  87. //          sessionID = 1;
  88. //          winner = false;
  89.           guessCounter = 1;
  90.           //announce this player has joined
  91.           textArea.append(new Date() + ": SinglePlayerGame is started now \n");
  92.           message = "You can start single player game now"+"\n";
  93.           outputToClient1.writeUTF(message);
  94.           outputToClient1.flush();
  95.           producePattern();
  96.           //game untill the player wins or number of guesses reaches 8;           
  97.           while(!(winner)) {
  98.             recNmatch();// compare pattern(chosen by server randomly)with client's guess
  99.             sendSingle();// a function for sending to just one client for it's singleplayer game
  100.             guessCounter++;
  101.             if(guessCounter == 9) {
  102.               String looser = "Limit is 8 tries, you lost.";
  103.               outputToClient1.writeUTF(looser);
  104.               outputToClient1.flush();
  105.               textArea.append("The singleplayer lost the game\n");
  106.               guessCounter = 0;
  107.               winner = true;
  108.               sessionID = 0;
  109.               break;
  110.             }
  111.           }
  112.         } else {//*********if it's multiplayer game,ensure that there are at least 2 players or more
  113.           // Notify that the player Player number
  114. //          new DataOutputStream(socket1.getOutputStream()).writeInt(sessionID);//Multi(1)send sessionID
  115. //          if (sessionID == 1) {
  116.           int showOrNot = inputFromClient1.readInt(); //read from client to decide showOPG!!!
  117. System.out.println("showOrNot(1)" + showOrNot);
  118. /*          if(showOrNot == 1)
  119.             showOPG = true;
  120.           else
  121.             showOPG = false;
  122. */
  123. //          }
  124. int sad = inputFromClient1.readInt();
  125. System.out.println(sad);
  126. System.out.println("test1");
  127. outputToClient1.writeInt(99);
  128. outputToClient1.flush();
  129. System.out.println("test2");
  130.           sessionID++;
  131.          
  132.           Socket socket2 = serverSocket.accept();
  133.           inputFromClient2 = new DataInputStream(socket2.getInputStream());
  134.           outputToClient2 = new DataOutputStream(socket2.getOutputStream());
  135. //                outputToClient2 = new DataOutputStream(socket2.getOutputStream()).writeInt(sessionID);
  136.           outputToClient2.writeInt(sessionID);
  137.           outputToClient2.flush();
  138. //          int show1 = 1, show2 = 2;
  139.  
  140.           outputToClient2.writeInt(showOrNot);
  141.           outputToClient2.flush();
  142. System.out.println("show or not = " + showOrNot);
  143. /*
  144.           if(showOPG){
  145.           //to send show or not to client 2
  146.             outputToClient2.writeInt(show1);
  147.             outputToClient2.flush();
  148.           } else {
  149.             outputToClient2.writeInt(show2);
  150.             outputToClient2.flush();
  151.           }
  152. */
  153.           int tempInt;
  154.           tempInt = inputFromClient2.readInt(); // input for multiplayer
  155. System.out.println("multi from cl 2(2) = " + tempInt);
  156. //                hTable.put(socket2, outputToClient2);//for broad casting later
  157. //                int temp = inputFromClient.readInt();
  158. sad = inputFromClient2.readInt();
  159. System.out.println(sad);
  160. System.out.println("test1");
  161. outputToClient2.writeInt(99);
  162. outputToClient2.flush();
  163. System.out.println("test2");
  164.  
  165. //####################################################################################
  166. //problem starts here as message is sent but not received by client
  167. //####################################################################################
  168. try { //makes player waits for 5 seconds
  169.   Thread.currentThread().sleep(5000);
  170. } catch (InterruptedException er) {
  171.   er.printStackTrace();
  172. }
  173.           String startMessage = "Two players now,You can start multiGame!";
  174. System.out.println("Test send message");
  175.           outputToClient2.writeUTF(startMessage);
  176.           outputToClient2.flush();
  177.           outputToClient1.writeUTF(startMessage);
  178.           outputToClient1.flush();
  179.  
  180. System.out.println("message sent");
  181.           textArea.append(new Date() + ": MultiPlayerGame is started now \n");
  182.           sessionID++;
  183.           producePattern();//before starting the game,produce the pattern for clients to guess
  184.           multiGameOn = true;
  185.           hTable.put(socket1, outputToClient1);
  186.           ServerThread player1 = new ServerThread(this,socket1);//create the first thread
  187.           hTable.put(socket2, outputToClient2);//for broad casting later
  188.           ServerThread player2 = new ServerThread(this,socket2);//create the second thread
  189.           player1.start();
  190.           player2.start();
  191.           while((!(winner)) && sessionID < 6) {
  192.  
  193.                 //create connection request
  194.                 socketMulti = serverSocket.accept();
  195.                 // Notify that the player Player number
  196.                 inputFromClient3 = new DataInputStream(socketMulti.getInputStream());
  197.                 outputToClient3 = new DataOutputStream(socketMulti.getOutputStream());
  198.                 outputToClient3.writeInt(sessionID);
  199.                 outputToClient3.flush();
  200.                 outputToClient3.writeUTF("Game is on alreay,Please enjoy watching...");
  201.                 outputToClient3.flush();
  202.                 //increase the session to keep track
  203.                 sessionID++;
  204.                 hTable.put(socketMulti, outputToClient3);//for broad casting later
  205.  
  206. //            int playersNoTurn = inputFromClient.readInt();
  207. //*///############################################################
  208.             // let the client know game is on. it's for player3 -6;
  209. //            if (sessionID > 2)
  210. //              new DataOutputStream(socketMulti.getOutputStream()).writeUTF("Game is on alreay,Please enjoy watching...");
  211. //            ServerThread player2 = new ServerThread(this,socketMulti);//create the second thread
  212. /*            if(sessionID == 2) {//***once there are 2 players, start the multigame!
  213.               producePattern();//before starting the game,produce the pattern for clients to guess
  214.               multiGameOn = true;
  215.               new DataOutputStream(socket1.getOutputStream()).writeUTF("Two players now,You can start multiGame!");
  216.               new DataOutputStream(socket2.getOutputStream()).writeUTF("Two players now,You can start multiGame!");
  217.               textArea.append(new Date() + ": MultiPlayerGame is started now \n");
  218.             }
  219. */
  220. /*
  221.             if(multiGameOn) {
  222. //              try {
  223.                 player1.start();//start the first thread
  224.                 if(winner)
  225.                   break;// if guess is right,then the game is over
  226. //                player1.sleep(5000);//after the first thread is finished it waits for 5 sec before another guess
  227.                 player2.start();//start the second thread
  228.                 if(winner)
  229.                   break;//if player2 guessed right,then the game is over
  230. //                player2.sleep(5000);//second thread waits for 5 sec before taking another guess
  231. //              } catch (InterruptedException ex) {
  232. //              }
  233.             }
  234.             if(sessionID == 6) {//when it's 6 players already,stop listening to connection request
  235. //              try {
  236.                 while(true) {
  237.                   player1.start();//start the first thread
  238.                   if(winner)
  239.                     break;// if guess is right,then the game is over
  240. //                  player1.sleep(5000);//after the first thread is finished it waits for 5 sec before another guess
  241.                   player2.start();//start the second thread
  242.                   if(winner)
  243.                     break;//if player2 guessed right,then the game is over
  244. //                  player2.sleep(5000);//second thread waits for 5 sec before taking another guess
  245.                 }
  246. //              } catch (InterruptedException ex) {
  247. //              }
  248.             }
  249. */
  250.  
  251.         // get info from client whether they wanna continue or not
  252.         //************if(continue){ gomeOn = ture;}  the while loop should depend on"gameOn"
  253.           }
  254.         }
  255.       }
  256.     } catch(IOException ex) {
  257.       System.err.println(ex);
  258.     }
  259.   }//end of receiveClient;
  260.  
  261.  
  262. //matching algo for player 1(single and multi player 1)
  263.   public void recNmatch() {
  264.     try{
  265.       finalBothMatch = 0;
  266.       finalColorMatch = 0;
  267.      
  268.       // receive the guess from client and put the guesses into an array
  269.       for(int i = 0; i < 4; i++){
  270.         guess[i] = inputFromClient1.readInt();//input guesses
  271.       }
  272.       //testing if the guess sent by client is arrived here*****************
  273.       System.out.print("User made guess of : ");
  274.       for(int i = 0; i < 4; i++)
  275.         System.out.print(guess[i]);
  276.       System.out.println("");
  277.      
  278.       int[] tempInp = new int[4]; //to hold another copy of the input
  279.       for (int i = 0; i < 4; i++) {
  280.         tempInp[i] = guess[i];//copy the input
  281.       }
  282.  
  283.       for (int i = 0; i < 4; i++) { // black and white matching algorithm
  284.         for (int j = 0; j < 4; j++) {
  285.           if(tempInp[j] == pattern[i]) {
  286.             finalColorMatch++; //increment white
  287.             tempInp[j] = -1; //to make sure the same value isn't counted again
  288.             j = 4; //to jump out of loop so others wouldn't be taken into account
  289.           }
  290.         }
  291.       }
  292.  
  293.       for (int i = 0; i < 4; i++) {
  294.         if (guess[i] == pattern[i]){ //matching color + position
  295.           finalBothMatch++;
  296.         }
  297.       }
  298.       finalColorMatch -= finalBothMatch; //matching color & wrong position
  299.  
  300.       if(finalBothMatch == 4) {
  301.         winner = true;
  302.         sessionID = 0;
  303.       }
  304.     } catch(IOException ex) {
  305.       System.err.println(ex);
  306.     }
  307.   }// end of recNmatch()
  308.  
  309.  
  310. //matching algo for multi player2
  311.   public void recNmatch2() {
  312.     try{
  313.       finalBothMatch = 0;
  314.       finalColorMatch = 0;
  315.      
  316.       // receive the guess from client and put the guesses into an array
  317.       for(int i = 0; i < 4; i++){
  318.         guess[i] = inputFromClient2.readInt();//input guesses
  319.       }
  320.       //testing if the guess sent by client is arrived here*****************
  321.       System.out.print("User made guess of : ");
  322.       for(int i = 0; i < 4; i++)
  323.         System.out.print(guess[i]);
  324.       System.out.println("");
  325.      
  326.       int[] tempInp = new int[4]; //to hold another copy of the input
  327.       for (int i = 0; i < 4; i++) {
  328.         tempInp[i] = guess[i];//copy the input
  329.       }
  330.  
  331.       for (int i = 0; i < 4; i++) { // black and white matching algorithm
  332.         for (int j = 0; j < 4; j++) {
  333.           if(tempInp[j] == pattern[i]) {
  334.             finalColorMatch++; //increment white
  335.             tempInp[j] = -1; //to make sure the same value isn't counted again
  336.             j = 4; //to jump out of loop so others wouldn't be taken into account
  337.           }
  338.         }
  339.       }
  340.  
  341.       for (int i = 0; i < 4; i++) {
  342.         if (guess[i] == pattern[i]){ //matching color + position
  343.           finalBothMatch++;
  344.         }
  345.       }
  346.       finalColorMatch -= finalBothMatch; //matching color & wrong position
  347.  
  348.       if(finalBothMatch == 4) {
  349.         winner = true;
  350.         sessionID = 0;
  351.       }
  352.     } catch(IOException ex) {
  353.       System.err.println(ex);
  354.     }
  355.   }// end of recNmatch2()
  356.  
  357.   //send these info(colorMatch and bothCnO) to a single client   
  358.   public void sendSingle() {
  359.     try {
  360.       outputToClient1.writeInt(finalBothMatch);
  361.       outputToClient1.flush();
  362.       //first check if the player winning or not
  363.       if(winner){
  364.         String winnerMsg = "Congratulations! you won with "+guessCounter+" guesses\n";
  365.         outputToClient1.writeUTF(winnerMsg);
  366.         outputToClient1.flush();
  367.         textArea.append("Player won with "+guessCounter+" guesses");
  368.       } else{
  369.         outputToClient1.writeInt(finalColorMatch);
  370.         outputToClient1.flush();
  371.         outputToClient1.writeInt(guessCounter);
  372.         outputToClient1.flush();
  373.       }
  374.     } catch(IOException ex) {
  375.       System.err.println(ex);
  376.     }
  377.   }
  378.  
  379.   //send these info(colorMatch and bothCnO) to a single client   
  380.   public void sendSingle1() {
  381.     try {
  382.       outputToClient2.writeInt(finalBothMatch);
  383.       outputToClient2.flush();
  384.       //first check if the player winning or not
  385.       if(winner){
  386.         String winnerMsg = "Congratulations! you won with "+guessCounter+" guesses\n";
  387.         outputToClient2.writeUTF(winnerMsg);
  388.         outputToClient2.flush();
  389.         textArea.append("Player won with "+guessCounter+" guesses");
  390.       } else{
  391.         outputToClient2.writeInt(finalColorMatch);
  392.         outputToClient2.flush();
  393.         outputToClient2.writeInt(guessCounter);
  394.         outputToClient2.flush();
  395.       }
  396.     } catch(IOException ex) {
  397.       System.err.println(ex);
  398.     }
  399.   }
  400.  
  401.   //send the info(color match and both match)to all the clients
  402.   public void broadcast(int playID) {
  403.     try {
  404.       for (Enumeration<DataOutputStream> e = getOutputStreams(); e.hasMoreElements();) {
  405.         DataOutputStream out = (DataOutputStream)e.nextElement();
  406.         // Write message
  407.         out.writeInt(1); //broadcast(1)send
  408. //#############################################################################################################
  409.         if(winner) {
  410.           String winnerMsg = "Player "+playID+" won! ";
  411.           out.writeUTF(winnerMsg);
  412.           for (int i = 0; i < 4; i++)
  413.             out.writeInt(guess[i]);
  414.           out.writeInt(finalBothMatch);
  415.           out.writeUTF(winnerMsg);
  416.           out.writeInt(finalColorMatch);
  417.         } else {
  418. //          out.writeInt(1);//let client broadcast listener know server seding game info
  419.           if(showOPG) {
  420.             String showing = "Player "+playID+" guessed ";
  421.             out.writeUTF(showing);
  422.             for (int i = 0; i < 4; i++)
  423.               out.writeInt(guess[i]);
  424.             out.writeInt(finalBothMatch);
  425.             out.writeInt(finalColorMatch);
  426.           } else {
  427.             String notShowing = "Player "+playID+" made a guess";
  428.             out.writeUTF(notShowing);
  429.             for (int i = 0; i < 4; i++)
  430.               out.writeInt(i);
  431.             out.writeInt(1);
  432.             out.writeInt(1);
  433.           }
  434.         }
  435.       }
  436.     } catch(IOException ex) {
  437.       System.err.println(ex);
  438.     }
  439.   }
  440.  
  441.   // this is method to take care of chatting system
  442.   private void chat(int plID) {
  443.     try {
  444.     // receive the message from a client
  445.       String string;
  446.       if (plID == 1)
  447.         string = inputFromClient1.readUTF();
  448.       else if (plID == 2)
  449.         string = inputFromClient2.readUTF();
  450.       else
  451.         string = inputFromClient3.readUTF();
  452.       // Send text back to all the clients
  453.       for (Enumeration<DataOutputStream> e = getOutputStreams(); e.hasMoreElements();) {
  454.         DataOutputStream out = (DataOutputStream)e.nextElement();
  455.         out.write(2);//inform the client receiver that it's a chat message
  456.         // Write message
  457.         String str = "Player "+plID+":"+ string;
  458.         out.writeUTF(str);
  459.         // Add chat to the server jta
  460.         textArea.append(str + "\n");
  461.       }
  462.     } catch(IOException ex) {
  463.       System.err.println(ex);
  464.     }
  465.   }
  466.  
  467.   // Used to get the output streams
  468.   Enumeration<DataOutputStream> getOutputStreams() {
  469.     return hTable.elements();
  470.   }
  471.  
  472.   //=================== server thread class=====================
  473.   class ServerThread extends Thread {
  474.     private server serv;
  475.     private Socket socket;
  476.     /** Construct a thread */
  477.     public ServerThread(server serv,Socket socket) {
  478.       this.socket = socket;
  479.       this.serv = serv;
  480.     }
  481.  
  482.     //====================run=================================
  483.     /** Implement the run() method for the thread */
  484.     public void run() {
  485.       try {
  486.         int chatOrGame = inputFromClient1.readInt();
  487.         int playID = inputFromClient1.readInt();
  488.         if(chatOrGame == 2) {
  489.           chat(playID)//receive string and broadcast it to all
  490.         } else {
  491.           recNmatch();// find out the color match and both match
  492.           broadcast(playID); // broadcast the guesses to all
  493.           try { //makes server waits for 5 seconds before new game starts
  494.             Thread.currentThread().sleep(5000);
  495.           } catch (InterruptedException er) {
  496.             er.printStackTrace();
  497.           }
  498.         }
  499.       } catch(IOException ex) {
  500.         System.err.println(ex);
  501.       }
  502.     }
  503.  
  504.     //================== annouce the multigame can be started=====
  505.     public void announce(){
  506.       try {
  507.       // Send text to all the clients
  508.         for (Enumeration<DataOutputStream> e = getOutputStreams(); e.hasMoreElements();) {
  509.           DataOutputStream out = (DataOutputStream)e.nextElement();
  510.           // Write message
  511.           String str = sessionID+" Players now, you can start Multigame!";
  512.           out.writeUTF(str);   
  513.           // Add chat to the server jta
  514.           textArea.append(str + '\n');
  515.         }
  516.       } catch(IOException ex) {
  517.         System.err.println(ex);
  518.       }
  519.     }
  520.   }//end of class ServerThread;   
  521.  
  522.   //============produce pattern ====================================
  523.   public void producePattern() {
  524.     for(int i=0; i<4; i++) {
  525.       pattern[i] = ((rand.nextInt(6))+1);
  526.     }
  527.   // *****test if the pattern[] is working properly
  528.     System.out.print("The secret pattern is : ");
  529.     for(int i=0;i<4;i++)
  530.       System.out.print(pattern[i]);
  531.     System.out.println("");
  532.     textArea.append("The secret pattern is "+pattern[0]+pattern[1]+pattern[2]+pattern[3]+"\n");
  533.   }
  534. }//end of program;

Update the Post

Either update this post and resubmit it with changes, or make a new post.

You may also comment on this post.

update paste below
details of the post (optional)

Note: Only the paste content is required, though the following information can be useful to others.

Save name / title?

(space separated, optional)



Please note that information posted here will expire by default in one month. If you do not want it to expire, please set the expiry time above. If it is set to expire, web search engines will not be allowed to index it prior to it expiring. Items that are not marked to expire will be indexable by search engines. Be careful with your passwords. All illegal activities will be reported and any information will be handed over to the authorities, so be good.

comments powered by Disqus
worth-right
worth-right