1

I am writing a multiplayer quiz application for two players (Clients) and I would like to have a mechanism which would allow only one player (the fastest to type the answer) to answer the question. So if for example: Player1 answers the question, Player2 immedietaly is moved to next question (just like Player1).

How can I make Server notify Client thread that the other Client answered the Question?

Client:

package com.company;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client
{
    private static Scanner scanner;

    private static BufferedReader serverReader;

    private static PrintWriter serverWriter;

    public static void main(String[] args)
    {
        try
        {
            connect();
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
    }

    public static void connect()
    {
        try( Socket clientSocket = new Socket( "localhost", 1236 ) )
        {
            scanner = new Scanner( System.in );
            serverReader = new BufferedReader( new InputStreamReader( clientSocket.getInputStream() ) );
            serverWriter = new PrintWriter( clientSocket.getOutputStream(), true );
            String serverResponse;
            while( ( serverResponse = serverReader.readLine() ) != null )
            {
                System.out.println( "[SERVER] - " + serverResponse );
                break;
            }
            for( int i = 0; i < 3; i++ )
            {
                System.out.println( "[SERVER] - " + serverReader.readLine() );
                System.out.print( "Your answer: " );
                String answer = scanner.nextLine();
                serverWriter.println( answer );
            }
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }
    }
}

Server:

package com.company;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Server
{
    private static final ArrayList< PrintWriter > writers = new ArrayList<>();

    private static final ArrayList< BufferedReader > readers = new ArrayList<>();

    private static final HashMap< String, Socket > players = new HashMap<>();

    private static final ArrayList< Question > questions = new ArrayList<>();

    public static void main( String[] args )
    {
        startServer();
    }

    public static void startServer()
    {
        questions.addAll( List.of( new Question( "2 + 2 = 4", "YES" ),
                new Question( "2 + 2 = 6", "NO" ), new Question( "2 + 2 = 8", "NO" ) ) );
        int i = 0;
        try( ServerSocket serverSocket = new ServerSocket( 1236 ) )
        {
            while( i < 2 )
            {
                Socket socket = serverSocket.accept();
                players.put( "Player" + ( i +  1 ), socket );
                System.out.println( "[CLIENT] - " + "Player" + ( i + 1 ) + " has joined the server." );

                i++;
                BufferedReader clientReader = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
                PrintWriter clientWriter = new PrintWriter( socket.getOutputStream(), true );
                writers.add( clientWriter );
                readers.add( clientReader );
            }
            writers.forEach( writer -> writer.println( "Game will start in 5 seconds" ) );
            try
            {
                Thread.sleep( 5000 );
            }
            catch ( InterruptedException e )
            {
                e.printStackTrace();
            }
            for( Question question : questions )
            {
                writers.forEach( writer -> writer.println( question.getContent() ) );

                // what to do now???
                while( true )
                {
                    // so server doesnt stop
                }
            }
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }
    }
}

Question:

package com.company;

public class Question
{
    private final String content;

    private final String  correctAnswer;

    public Question( String aContent, String aCorrectAnswer )
    {
        content = aContent;
        correctAnswer = aCorrectAnswer;
    }

    public String getContent()
    {
        return content;
    }

    public String getCorrectAnswer()
    {
        return correctAnswer;
    }
}
micmus4
  • 41
  • 1
  • 3
  • Since you already cached the client sockets, you can just use their outputstreams (like you did in the beginning using PrintWriter) to message them to continue with the next Question. Now the handling just needs to be added in the client. – Tobias Cremer Dec 26 '21 at 20:47
  • @TobiasCremer okay, but how exactly can this be achieved? Let's say player 1 sends an answer and player 2 is at "String answer = scanner.nextLine();" line of code at the moment. How would player2 notice it exactly? I assume I need to add an 'if' which would check if serverReader.readLine() gets a specific message, but player2 would still have to answer the question in order for that line of code to be executed. And how can server know which player sent him message? I have all sockets' readers cached, but how can I wait for input for JUST one of them in order to execute some actions? – micmus4 Dec 26 '21 at 21:05
  • I do understand the problem now. I think it can be solved in changing your infrastructure. If you want to stay with you current structure you need to perform the input handling of the client in a different thread than the server-client communication. – Tobias Cremer Dec 26 '21 at 21:09
  • @TobiasCremer before, I tried to make a seperate thread for every connection to the server, but I also couldn't go further from there. https://stackoverflow.com/questions/70486514/how-can-client-threads-be-synchronized-in-tcp-client-server-connection – micmus4 Dec 26 '21 at 21:11
  • If you want I can write you the code you need with a small explanation (just the client-server connection). Im having problems describing it :/ – Tobias Cremer Dec 26 '21 at 21:12
  • @TobiasCremer if it's not a problem then yeah, I would really appreciate it! – micmus4 Dec 26 '21 at 21:14
  • Do you maybe want to chat via a different platform? I think we could communicate a bit better – Tobias Cremer Dec 26 '21 at 21:23
  • Yeah, as far I know there isn't a possibility to private chat on Stackoverflow, so perhaps Discord? – micmus4 Dec 26 '21 at 21:28
  • You can add me: Txb1#0083 – Tobias Cremer Dec 26 '21 at 21:31

0 Answers0