I'm trying to reprodruce a client-server architecture in order to understand java sockets. So I have a client that sends a message to the server, and the server just "say" something like "(Server) "

So here we go :

public class ServeurTCP {

static ServerSocket socketServeur;
static Socket socketVersUnClient;
static BufferedReader in;
static PrintWriter out;

public static void main(String[] args){
    //attente des connexions sur le port 9999

    //traitement des exceptions
    try {
        socketServeur = new ServerSocket(9999);

    } catch (IOException e) {
        e.printStackTrace();
    }


    //dans une boucle pour chaque socket clientes, appeler traiterSocketClient
    while(true)
    {   
        try {
            socketVersUnClient = socketServeur.accept();
            System.out.println("Attente des clients");

            in = creerReader(socketVersUnClient);
            out = creerPrinter(socketVersUnClient);
            envoyerMessage(out,"test");
            System.out.println(recevoirMessage(in));
            traiterSocketClient(socketVersUnClient);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

public static void traiterSocketClient(Socket socketVersUnClient) {
    //Créer printer et reader


    //Tant qu'il y'a message à lire via recevoirMessage
    while(!recevoirMessage(in).equals("fin"))
    {
        System.out.println("ici");
        //Envoyer message client via envoyerMessage
        try {
            envoyerMessage(out,"(Serveur) message : "+in.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally
        {
            try{
                socketVersUnClient.close();
            } catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

public static BufferedReader creerReader(Socket socketVersUnClient) 
{
    //crée BufferedReader associé à la socket
    try {
        return new BufferedReader(new InputStreamReader(socketVersUnClient.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

public static PrintWriter creerPrinter(Socket socketVersUnClient) 
{
    //crée PrintWriter associé à la socket
    try {
        return new PrintWriter(socketVersUnClient.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

public static String recevoirMessage(BufferedReader reader) 
{

    //Récupérer une ligne
    String userInput = null;

    try {
        userInput = reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }


    //Retourner la ligne lue ou null si aucune ligne à lire
    return userInput;
}

public static void envoyerMessage(PrintWriter printer, String message) throws IOException
{
    System.out.println("Message");
    //envoyer le message vers client
    printer.write(message);
    printer.flush();
}
}

This is my Client Class

public class ClientTCP {

static Socket socketClient;
static BufferedReader in;
static BufferedReader clientReader;
static String message;
static PrintWriter out;


public static void main(String[] args) 
{
    //créer une socket client
    try {
        socketClient = new Socket("localhost",9999);

    } catch (IOException e) {
        e.printStackTrace();
    }

    //créer reader et writer associés
    in = creerReader(socketClient);
    out = creerPrinter(socketClient);

    clientReader = new BufferedReader(new InputStreamReader(System.in));

    while( ((message = lireMessageAuClavier()) != "fin"))
    {
        //envoyer le message au serveur
        envoyerMessage(out,"(Client) message : "+message);

        //recevoir et afficher la réponse du serveur
        recevoirMessage(in);
    }

}

public static String lireMessageAuClavier() {


    //lit un message au clavier en utilisant par exemple un buefferedReader
    //sur System.in

    try {
        return clientReader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;

}

public static BufferedReader creerReader(Socket socketVersUnClient) 
{
    //crée BufferedReader associé à la socket
    try {
        in = new BufferedReader(new InputStreamReader(socketVersUnClient.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    return in;
}

public static PrintWriter creerPrinter(Socket socketVersUnClient) 
{
    //crée PrintWriter associé à la socket
    try {
        out = new PrintWriter(socketVersUnClient.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return out;
}

public static String recevoirMessage(BufferedReader reader) 
{
    //Récupérer une ligne
    String userInput = null;

    try {

        userInput = reader.readLine();

    } catch (IOException e) {
        e.printStackTrace();
    }       

    //Retourner la ligne lue ou null si aucune ligne à lire
    return userInput;

}

public static void envoyerMessage(PrintWriter printer, String message) 
{
    //envoyer le message vers client
    printer.write(message);

    printer.flush();
}

It seems that the problem is bad connection between both class, for example i can't send a single message from my server to my client, and I don't get why.

有帮助吗?

解决方案

With some quick fixes it will sort of work:

  1. In the server, in envoyerMessage, add a newline at the end of the message: printer.write(message + "\n"); The client is reading from the server using clientReader.readLine, and so it would be stuck until it receives a newline.
  2. In the client, in main, fix the string comparison to use ...equals("fin") instead of !=, otherwise no matter what you enter, the while loop will never end.

As you are working on this, I recommend to work on the server first and use telnet as your client:

telnet localhost 9999

After the basic stuff works, try things like:

  • Connect 2-3 times in a row: can the server handle that correctly?
  • Connect from 2-3 windows at the same time: can the server handle concurrent clients? (Ok this might be beyond your scope...)

After the server works well, work on the client (to replace telnet).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top