Solved

Java bingo problems

Posted on 2001-07-18
8
541 Views
Last Modified: 2008-02-26
hi there,
I am developing a bingo game in java. The scenario is such that the client is generating the numbers on the bingo cards. Now i allow 4 users at a time to play this game. I also want my client to see the other 3 cards of the other users. In trying this, whenever my client is loaded i create a serializable object DataAcross with string username and an int[] numbers that can store my username a 24 values. On connecting to the server, i send my data through the ObjectOutputStream to the server. The process is simple, all the four cards send in their values to the server when they connect to the server and then expect back the entire 4 cards information (username and their corresponding array back). Now what is happening here is that say i as client1 connect first, the problem is that i send my data and am expecting back the data for all the four players, but the other players have not yet connected to the client. So i do not get all the 4 values back. Instead i get only my information back and thus my client goes into an exception since it was expected to get all the values and is getting back only 1. Now I have tried making the client sleep for 60 seconds before it can take back the data, so that i buy time for all the clients to log in and send the data so that after 60 seconds i can get back all the data. But it is not working. The client that logs in the last (also the current thread in client) gets all the values, whereas the clients that have logged in previously do not get any values. Is it because the server cannot keep a track of the previous threads of clients..and thus the final thread is the only thread that must be receiving the data.....or is it some other reason. I think if there is a means to keep these spawned threads in some form of a vector or something i should be able to send the values to all the clients. Either ways i would like you to help me in it.
i hope this helps
regards,
anup
0
Comment
Question by:amarwadi
  • 3
  • 3
  • 2
8 Comments
 
LVL 92

Expert Comment

by:objects
Comment Utility
Need to see some code.
But sounds like you need the server to wait until it's got all 4 players data before it sends replies to all the clients.
0
 

Expert Comment

by:abhinavkaushik
Comment Utility
I am sending you the server code. Basically what you have to do is that on the server side, you have to define a shared memory space on the server side, the reference of which is passed to every ClientHandling class which the server creates. The interaction between the client and server is through ObjectOutputStream and ObjectInputStream. The classes are as follows:
ClientData.java - class for holding the client data.
ClientDataHolder.java -  class which holds all ClientData. This class implements the shared memory which I was talking about above.
BingoServer.java - the actual server class
BingoServerThread.java - client handler class. The server creates a new instance of this class for each client and passes a reference to an instance of ClientDataHolder. Whenever a client sends an instance of ClientData class, it is added to the instance of ClientDataHolder. Then this class sends back a clone of the instance of ClientDataHolder to the client. Remember that the ClientDataHolder is sent as an Object class which you will have to cast back to ClientDataHolder on the client side.

On the client side you don't have to wait for 60 seconds for all players to log on. When the client thread receives the instance of ClientDataHolder, it checks the size and if size is not as expected, simply put it to sleep.
The code:

BingoServer.java
====================
import java.net.*;
import java.io.*;

public class BingoServer
{
    public static void main(String[] args) throws IOException
    {
        ServerSocket serverSocket = null;
        boolean listening = true;
          ClientDataHolder cdh = new ClientDataHolder();

        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(-1);
        }

        while (listening)
              new BingoServerThread(cdh, serverSocket.accept()).start();

        serverSocket.close();
    }
}

=======================
BingoServerThread.java
=======================
import java.net.*;
import java.io.*;

public class BingoServerThread extends Thread
{
     private ClientDataHolder cdh;
     private Socket socket;

     public BingoServerThread(ClientDataHolder cdh, Socket socket)
     {
          this.cdh = cdh;
          this.socket = socket;
     }

     public void run()
     {
          try
          {
               ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
               ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());

               cdh.add((ClientData)in.readObject());
               out.writeObject(cdh);
          }
          catch(Exception e){System.out.println("Exception e:" + e.getMessage());}
     }
}

==========================
ClientData.java
==========================
import java.io.*;

public class ClientData implements Serializable
{
     private String name;
     private int[] data;

     public ClientData(String name, int data[])
     {
          this.name = name;
          this.data = data;
     }

     public String getName()
     {
          return name;
     }

     public int[] getData()
     {
          return data;
     }
}

===========================
ClientDataHolder.java
===========================
import java.io.*;
import java.util.*;

public class ClientDataHolder implements Serializable
{
     private Vector holder;

     public ClientDataHolder()
     {
          holder = new Vector();
     }

     public void add(ClientData data)
     {
          holder.addElement(data);
     }

     public Object getData()
     {
          return holder.clone();
     }

        public int getSize()
        {
               return holder.size();
        }
}
0
 

Author Comment

by:amarwadi
Comment Utility
hi there,
i read your comment on the server modifications. Now as far as my client is concerned this piece of code should give u an idea of what is happening:
 
DataAcross da=new DataAcross(gui.username,countTotal);
      oos.writeObject(da);
     
      cdh=(DataAcrossHolder)ois.readObject();
     
      int users=cdh.getSize();
      System.out.println(users+ " USERS");
     /***IS THIS CORRECT***/
      while(users!=2){
           sleep(5000);
           //cdh=(DataAcrossHolder)ois.readObject();
            //users=cdh.getSize();
      }
     
      d=(Vector)cdh.getData();
      for(int i=0;i<d.size();i++){
           System.out.println(((DataAcross)(d.elementAt(i))).getName());
           int[] a=((DataAcross)(d.elementAt(i))).getData();
           for(int o=0;o<a.length;o++){
                System.out.println(a[o]);
           }
      }


here the DataAcross and the DataAcrossHolder are your ClientData and ClientDataHolder respectively. Now how will my client be updated when both the users log in. I dont know how to access this CDH and then call my display cards method. BOth My Clients should get both the records. But how will my clients know when CDH is updated?? Or how do i make my client function
can u please help??
regards,
anup
0
 

Author Comment

by:amarwadi
Comment Utility
the latest here is as follows...
i have tried implementing a lot of the issues that you have stated here. but the first client is only getting it's card. The second card is getting 2 cards, and the third is getting 3 cards. Is there some problem with the logic....I have the zip file of this code set up on

http://amarwadi.hypermart.net/dummyjava9.zip

The client directory has a file called the NetworkClient.java that sends the client data to the server. The server side has the files ConnectionDirector, the BingoServer and the ServerThread, which are important from our perspective. The ServerThread is the one that does all the communication.
To run this code, open up 3 html files, client1,client2,client3.html and at serverside run java ServerStarter at the dos prompt. A window will pop up asking for the number of users, enter in 3 and then click ok
to connect the client just click on Start Playing Bingo.(There is no need to enter in the username, the html tag takes care of that). If u run the java console then u can see the operations taking place.
I hope this helps
regards,
anup
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 92

Expert Comment

by:objects
Comment Utility
Your server still needs to wait until every ones logged in before it returns the client data to each client.
Otherwise you need some mecahnism to inform clients of new users logging in.
0
 

Accepted Solution

by:
abhinavkaushik earned 200 total points
Comment Utility
I am sending you the full code with the client code also included. There are some modifications to the code on the server side also. Now the code is working fine.
There is how you run the code.
You start the server with:
java BingoServer

You start the client with:
java BingoClient <clientname> <any integer>

Whenever a client login, and if it finds that a client has already logged, it prints "new player logged in.". Afterwards, if a new client logs in, it prints the same message. Else, it keeps printing "No new player logged in".

This code should be able to solve your problem.
=================================
BingoClient.java
=================================
import java.net.*;
import java.io.*;

public class BingoClient extends Thread
{
      private ClientDataHolder cdh;
      private ClientData cd;
      private int numberOfClients = 1;
      ObjectOutputStream out;
      ObjectInputStream in;

      Socket socket;
      public BingoClient(String name, int start)
      {
            int [] a = new int[24];
            for(int i = 0; i < 24; i++)
            {
                  a[i] = start++;
            }
            cd = new ClientData(name,a);

      }

      public void connect()
      {
            try
            {
                  socket = new Socket("localhost",4444);
                  out = new ObjectOutputStream(socket.getOutputStream());
                  in = new ObjectInputStream(socket.getInputStream());
            }
            catch(Exception e){System.out.println("Exception: " + e.getMessage());}
      }


      public void run()
      {
            while(true)
            {
                  try
                  {
                        out.writeObject(cd);

                        cdh = (ClientDataHolder)in.readObject();

                        if(cdh.size() <= numberOfClients)
                              System.out.println("No new player logged in.");
                        else
                        {
                              System.out.println("new player logged in.");
                        }
                        numberOfClients = cdh.size();
                        sleep(5000);
                  }
                  catch(Exception e){System.out.println("Exception: " + e.getMessage());}
            }

      }

      public static void main(String args[])
      {
            int s = Integer.parseInt(args[1]);
            BingoClient bc = new BingoClient(args[0],s );
            bc.connect();
            bc.start();
      }
}

==================================
BingoServer.java
==================================
import java.net.*;
import java.io.*;

public class BingoServer
{
    public static void main(String[] args) throws IOException
    {
        ServerSocket serverSocket = null;
        boolean listening = true;
            ClientDataHolder cdh = new ClientDataHolder();

        try {
            serverSocket = new ServerSocket(4444);
            System.out.println("waiting");
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(-1);
        }

        while (listening)
                new BingoServerThread(cdh, serverSocket.accept()).start();

        serverSocket.close();
    }
}

==============================
BingoServerThread.java
==============================
import java.net.*;
import java.io.*;

public class BingoServerThread extends Thread
{
      private ClientDataHolder cdh;
      private Socket socket;
      ObjectInputStream in;
      ObjectOutputStream out;

      public BingoServerThread(ClientDataHolder cdh, Socket socket)
      {
            this.cdh = cdh;
            this.socket = socket;
            try
            {
                  in = new ObjectInputStream(socket.getInputStream());
                  out = new ObjectOutputStream(socket.getOutputStream());
            }
            catch(Exception e){System.out.println("Exception e:" + e.getMessage());}
      }

      public void run()
      {
            while(true)
            {
                  try
                  {
                        cdh.add((ClientData)in.readObject());
                        ClientDataHolder temp = (ClientDataHolder)cdh.clone();
                        out.writeObject(temp);
                  }
                  catch(Exception e){System.out.println("Exception e:" + e.getMessage());}
            }
      }
}

=================================
ClientData.java
=================================
import java.io.*;

public class ClientData implements Serializable
{
      private String name;
      private int[] data;

      public ClientData(String name, int data[])
      {
            this.name = name;
            this.data = data;
      }

      public String getName()
      {
            return name;
      }

      public int[] getData()
      {
            return data;
      }

      public String toString()
      {
            String message = "\nclient name:" + name;
            message = message + "data:";
            for(int i = 0; i < data.length; i++)
            {
                  message = message + Integer.toString(data[i]);
            }

            return message;
      }
}

============================
ClientDataHolder.java
============================
import java.io.*;
import java.util.*;

public class ClientDataHolder implements Serializable, Cloneable
{
      private Vector holder;

      public ClientDataHolder()
      {
            holder = new Vector();
      }

      public void add(ClientData data)
      {
            boolean found = false;

            for(int i = 0; i < holder.size(); i++)
            {
                  ClientData cd = (ClientData)holder.elementAt(i);
                  String name = cd.getName();
                  if(name.equals(data.getName()))
                  {
                        cd = data;
                        found = true;
                  }
            }
            if(!found)
            {
                  holder.addElement(data);
            }
      }

      public int size()
      {
            return holder.size();
      }

      public Object clone()
      {
            ClientDataHolder temp = new ClientDataHolder();
            temp.holder = (Vector)this.holder.clone();
            return temp;
      }

      public Enumeration enumerate()
      {
            return holder.elements();
      }

      public ClientData get(int index)
      {
            return (ClientData)holder.elementAt(index);
      }
}

0
 
LVL 92

Expert Comment

by:objects
Comment Utility
WHen a client logs in, the server needs to create the connection but not send out the client data, it just remains idle. And the client waits for data from the server.
Then when another client logs in do the same.
Similarily for the third.
Once the fourth client logs in, THEN the server should send out the client data to ALL 4 clients.

Is that the functionality u require?
0
 

Author Comment

by:amarwadi
Comment Utility
Actually, i figured out the problem, but the whole concept that you provided was amazing. Keep it up buddy
regards,
anup
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now