I was tasked to do a 2-4 player network card game. Before I jumped into doing the card game. I decided to try out
an a simple program which is the clients taking turns to type in their textfield.
I have a server that listens to 3 incoming client connections. once all 3 clients is being connected,
Steps
1) The first client will send the message first while the second and third client will wait for the first client to finish sending.
2) After the first client finished sending the message, it will be second client turn to send the message and the third client will wait for the second client to send finish.
3) After the third client finished sending the message, it will be third client turn to send the message and the first client will wait for the third client to send finish and (go back to step 1))
**The first client can only start typing once all 3 clients is being connected**
In my server class,I spawn a new Thread once a client is connected, I do a wait() on each time the client is being connected, I stored the thread in a arraylist as well. I have an id to keep track how many clients is currently connected. once the id reaches 3, I used notifyall() to notify all the threads and set the first position of my arraylist as my currentThread so that I can keep track which is the currentThread running.
I started 3 clients. and I typed the textfield of the first client but my server isn't receiving any messages.
class Server implements Runnable { private List<SpawnNewThread> sntList = new ArrayList<SpawnNewThread>(); private SpawnNewThread currentThread; private int id = 0; @Override public void run() { try { ServerSocket sSocket = new ServerSocket(4444); while(true) { Socket socket = sSocket.accept(); id++; SpawnNewThread snt = new SpawnNewThread(socket); /*wait for 2 more clients to connect before the first client can enter a text in the textField*/ snt.wait(); sntList.add(snt); if(id == 3) { //notify all threads if 3 clients is being connected notifyAll(); //set the first thread in the sntList to first thread currentThread = sntList.get(0); } snt.start(); } } catch(IOException exception) { System.out.println("Error: " + exception); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
I think my logic is wrong and I really need help on how to implemented a turn-based program.