1

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.

Charles
  • 50,943
  • 13
  • 104
  • 142
TLR
  • 577
  • 3
  • 8
  • 24
  • 1
    One general tip for testing socket stuff: Test your server with telnet or a similar terminal program (on linux/unix/mac, start your server, then open a shell and type `telnet localhost 9999`. This will reduce the search space for bugs to the server. – Stefan Haustein Feb 16 '14 at 15:07
  • 2
    I'm french too and I understand what you wrote, but that would be easier for others if your code example was in english (sendMessage, receiveMessage) to get what you're doing inside your loops etc – Pierre Feb 16 '14 at 15:14
  • 1
    Comparing Strings in Java like `(message = lireMessageAuClavier()) != "fin"` doesn't work. Maybe learn the basics before messing around with sockets. – Reboot Feb 16 '14 at 15:15
  • Yeah use .equals() for Strings comparison. – Pierre Feb 16 '14 at 15:16
  • Please note that tags stand alone. That is, you can't combine multiple tags to create a single concept. The tags `[client]` and `[server]` together aren't the same thing as the single `[client-server]` tag. Always be sure to read the descriptions that appear when selecting tags! – Charles Feb 17 '14 at 06:19
  • You've overdone this. You don't need a method whose only purpose is to read a line, write a line, whatever, and catch an exception. Just call `readLine(),` `println(),` or whatever directly and enclose *all* the code in a *single* try/catch block. – user207421 Feb 17 '14 at 06:24

1 Answers1

0

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).

janos
  • 120,954
  • 29
  • 226
  • 236