Client-Server-Client communication using Sockets

后端 未结 3 2032
旧巷少年郎
旧巷少年郎 2020-12-14 05:06

I am building a small chat application in which client A wants to send something to client C with server B in between. First of all is this a correct approach for the proble

3条回答
  •  青春惊慌失措
    2020-12-14 05:45

    If I am not mistaken, you must be having a problem with receiving a message from the Server or SSocket class. What happens with your code is that when you send a message from the client to the server the Server class receives your messages also gives an echo of the message in the client. However, when you send a message from the Server class, you don't get any messages in the Client Class.

    To get this to work, you would have to modify your code in the following fashion:

    SSocket Class

    String line = null;
    while (true) {
        line = dIn.readUTF();
        System.out.println("Recievd the line----" + line);
        dOut.writeUTF(line + " Comming back from the server");
        dOut.flush();
        System.out.println("waiting for the next line....");
    }
    

    You should add these lines:

    String Line2 = take.nextLine(); //The user types a message for the client
    dOut.writeUTF(Line2 + " Comming back from the server"); //The message is sent to the client
    

    Replace the while loop with this one and it will work fine.

    while (true) {       
        line = dIn.readUTF(); //Takes the msg from the client
        System.out.println("Recievd the line----" + line); //Prints the taken message
    
        String Line2 = take.nextLine(); //The user types a message for the client
        dOut.writeUTF(Line2 + " Comming back from the server"); //The message is sent to the client
        dOut.flush();
        System.out.println("waiting for the next line....");
    }
    

提交回复
热议问题