0

So, right now, the only thing I've managed to do, is, on connect, pw.printin("Hi"). Now the receiving side of the client may reply with "Hello", and if it does, I want to answer with "Hi" , and then have it reply with "Hello" again, in an endless loop that only gets interrupted in another if statement.

try {
            ServerSocket serverSocket = new ServerSocket(90);
            while(true) {
                String str= "Hello";                
                Socket socket = serverSocket.accept();
                OutputStream os = socket.getOutputStream();
                PrintWriter pw = new PrintWriter(os, true);
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                pw.println("Hi");
                if(br.readLine().equals(str)){
                    pw.println("Hi");
                }
                System.out.println(str);
            }
        } catch (IOException e) {
                try {
                    if(serverSocket!= null){
                    serverSocket.close();
                    }
                }
                 catch (IOException e1){

                    e1.printStackTrace(System.err);
                }
            }
        return 500;
    }
}
user207421
  • 305,947
  • 44
  • 307
  • 483
BioPipeRex
  • 15
  • 5
  • For start, compare strings using `equals()` method. `==` compares memory addresses, not string contents. – Miskov Jun 05 '16 at 18:24
  • ah, ofcourse, however that wasn't the issue i was having, i don't think so atleast. – BioPipeRex Jun 05 '16 at 18:35
  • What is your problem right now? I'm sorry, but i'm unable to find the particular one from the description. What have you achieved so far? – Miskov Jun 05 '16 at 18:48
  • When receiver gets the message "hi", and replies with "hello", i want to say hi back. and not stop there. so, Receiver connects , code says Hi to him , if he replies with " Hello " , code replies to him again with " Hi " , if he replies again with " Hello " , and it will keep saying " HI " to him, as long as he's saying " Hello " and that keeps going on and on and on, until, he replies with " bye " when server/port receives " bye " , it closes the socket. – BioPipeRex Jun 05 '16 at 19:03
  • Does your code compile? The `serverSocket` in catch block is out of scope in your code. Furthermore, the `Socket socket` hangs until the connection is made, so in fact your server is always printing one `hi`, then eventually it prints another one. – Miskov Jun 05 '16 at 19:13
  • It compiles yes, and yes, that's my exact problem. It says one "Hi" and then there's absolutely nothing else it does.... so when i reply to it with Hello. It does nothing, when actually i want it to reply with Hi again. – BioPipeRex Jun 05 '16 at 19:21
  • I've made a solution which seems to solve your problem. Please, accept it if it's correct. – Miskov Jun 05 '16 at 19:56
  • Your solution still presents 2 problems. When Receiver connects , it says hi, which is great, but it's always ignoring the first " Hello " , took a small screenshot," Hello " was typed manually by me, Hi, was replied automatically per the code you helped me with. So you can see that it ignored first " Hello " . https://gyazo.com/31799ff3e214a5b0cb4dcee1e6f811ac The second problem, when i close my telnet, and reopen it and connect to the same port again, it doesn't do anything. Despite not having said "Bye" , which makes me think that the socket got closed, or is just not responding anymore. – BioPipeRex Jun 05 '16 at 20:24
  • It's strange. MS telnet works just fine – Miskov Jun 05 '16 at 20:32
  • Strange, i've done it a few times with the same result.. Can you tell me where you opened your ServerSocket serverSocket = new ServerSocket(90); – BioPipeRex Jun 05 '16 at 20:42
  • Just before the `try` block in order to be visible in `catch` – Miskov Jun 05 '16 at 20:43
  • I put just after the try block, before the strings, but tried to put it before the try with the same issue. Going to try a different telnet service. – BioPipeRex Jun 05 '16 at 20:52
  • Bare in mind, that if you close your connection in any other way than saying `Bye`, the server should stop or hang. Additional code is required for solving that issue – Miskov Jun 05 '16 at 20:55
  • Ah, that explains the hanging issue. However i'm still stuck with having to say 2 "Hello"s before the "Hi" start coming. I'm using putty, can't use ms telnet since it never wants to install for me. But that's beside the point. Is there any thing you can think of why it's taking 2 "Hello" before it starts saying Hi? – BioPipeRex Jun 05 '16 at 21:06
  • For some reason, the first message from putty contains some additional characters, so the code is nearly as ok. I've added `replaceAll("[^A-Za-z0-9]", "")` to remove non alphanumerical characters from input according to [link](http://stackoverflow.com/questions/1805518/replacing-all-non-alphanumeric-characters-with-empty-strings). The answer is edited. – Miskov Jun 05 '16 at 21:19
  • Works beyond perfectly! You're awesome!!!! Is this what i should use if i'm not using putty too. or should i use the first one for nonputty, 2nd one for putty? Will choose your answer as an answer Right away. And can you recommend on what i should research to solve the closing the client without bye? Thanks :) – BioPipeRex Jun 05 '16 at 21:33
  • You can use it with any client, but keep in mind that this removes any non alphanumerical characters. If such character will be added, the message will be skipped. Also, if you want to enable non alphanumrical characters as messages, you have to change your code. To solve the closing issue, you can try to put the `try` block inside the `while(true)` loop, so an exception wouldn't break it. Play around, it's the only way to learn :) – Miskov Jun 05 '16 at 21:36
  • Thank you so much Miskov! Accepted your answer, will definitely try play around with it, and have an untouched one saved :D , You made someone about to pull his hair very happy! Have a great day!!!! – BioPipeRex Jun 05 '16 at 21:44

1 Answers1

0

Your problem is, that there is no actual loop for repeatedly saying hi to the client, you have to make it. The Socket socket = serverSocket.accept(); part is for dealing with one client, so the while(true) loop just keeps the server alive for multiple clients to connect. Thus, you have to make the inner loop (preferably the other thread/thread pool for client in more serious scenario) to make per-client logic.

The sample of such loop:

try {
    String str = "Hello";
    String endingStr = "Bye";
    while (true) {
        Socket socket = serverSocket.accept();
        OutputStream os = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(os, true);
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        pw.println("Hi");
        while ((input = br.readLine()) != null) { //Here is the loop part
            input = input.replaceAll("[^A-Za-z0-9]", "");
            if(input.equals(endingStr)){
                break;
            }

            if (input.equals(str)) {
                pw.println("Hi");
            }
        }
        socket.close();
    }
} catch (IOException ex) {
    try {
        if (serverSocket != null) {
            serverSocket.close();
        }
    } catch (IOException e1) {

        e1.printStackTrace(System.err);
    }
}

EDIT: changed code to prevent NPE as suggested by EJP

Miskov
  • 178
  • 12
  • Every `readLine()` result must be checked for null. The normal way to write the loop is `while ((input = br.readLine()) != null)`. Your way there will be NPEs when the client disconnects. – user207421 Jun 06 '16 at 01:58
  • I've changed my answer. – Miskov Jun 06 '16 at 08:46