BioPipeRex BioPipeRex - 5 months ago 17
Java Question

Receiving and replying with data over a socket

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;
}
}

Answer

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");
            String input = br.readLine().replaceAll("[^A-Za-z0-9]", "");
            while (!input.equals(endingStr)) { //Here is the loop part
                if (input.equals(str)) {
                    pw.println("Hi");
                }
                input = br.readLine().replaceAll("[^A-Za-z0-9]", "");
            }
            socket.close();
        }
    } catch (IOException ex) {
        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
        } catch (IOException e1) {

            e1.printStackTrace(System.err);
        }
    }
Comments