13

I have a simple client server program. Server can accept connection from multiple clients. Currently this is what is occurring in my client.
1) Type LIST in client. Server will send back all the files in current directory to client. 2) Type "Hello" in client. Server should send back "Hello". However, in the client the client reads blank.
I enter "QUIT" in client. I only see the Hello msg back from the server.
I cannot figure out why the client does not read the Hello msg after it is sent back by the Server.

Client Code

import java.net.*;   // Contains Socket classes
import java.io.*;    // Contains Input/Output classes
import java.nio.CharBuffer;

class ClntpracticeSandbox{

   public static void main(String argv[]){


   try{
//     
       Socket client=new Socket("localhost", 7777);
       System.out.println("Connected to server " + client.getInetAddress() 
             + ": " + client.getPort());
       System.out.println("local port is " + client.getLocalPort());

       BufferedReader kbreader;
       BufferedWriter writer;
       BufferedReader reader;

       kbreader = new BufferedReader(new InputStreamReader(System.in));
       writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
       reader = new BufferedReader(new InputStreamReader(client.getInputStream()));

       String data = "", datakb, line=null;

       do{
            System.out.print("Text to the server? ");
            datakb = kbreader.readLine();
            writer.write(datakb);
            writer.newLine();
            writer.flush();

            System.out.print("Received from the Server:  ");
            line = reader.readLine();
            while (line.equals("")==false){
                System.out.println(line);
                line = reader.readLine();
            }
       } while (datakb.trim().equals("QUIT")==false);          
       client.close();
       System.exit(0);

      }catch(Exception e){
          System.err.println("Exception: " + e.toString());
      }
   }
}

Server Code

import java.net.*;   // Contains Socket classes
import java.io.*;    // Contains Input/Output classes
import java.nio.file.*;

class SrvrpracticeSandbox{
    public static void main(String argv[]) throws IOException {
        ServerSocket s = new ServerSocket(7777);

        System.out.println("Server waiting for client on port " + s.getLocalPort());
        int count = 0;
        do {
            count = count + 1;
            Socket connected = s.accept();
            new clientThread(connected, count).start();
        } while (true);

    }
}

class clientThread extends Thread {

    Socket myclientSocket = null;
    int mycount;
    DataInputStream is = null;
    PrintStream os = null;


    public clientThread(Socket clientSocket, int count) {
        this.myclientSocket = clientSocket;
        this.mycount = count;
    }

    public void run() {
        try {

            System.out.println("New connection accepted " + myclientSocket.getInetAddress() + ": " + myclientSocket.getPort());

            BufferedReader reader;
            BufferedWriter writer;

            reader = new BufferedReader(new InputStreamReader(myclientSocket.getInputStream()));
            writer = new BufferedWriter(new OutputStreamWriter(myclientSocket.getOutputStream()));

            String data; 
            String testdirectory = "file1.txt\nfile2.txt\nfile3.txt";
            do{
                data = reader.readLine();
                System.out.println("Received from " +mycount + ":" + data);
                if (data.equals("LIST")) {
                    writer.write(mycount + "\n"+"150 - Transfer Initiated."+"\n"+
                            "DATA " +returnDirectoryList().getBytes().length + "\n" + 
                            returnDirectoryList() + "\r\n"); 
                } else {
                    writer.write("Server Echos to " + mycount + ":"+ data + "\n"+"This is a new line."+"\r\n"); 
                }                
                writer.newLine();
                writer.flush();

            }while (data.equals("QUIT") == false); 

            myclientSocket.close();
            System.exit(0);
        } catch (IOException ex) {
        }
    }
    private String returnDirectoryList()
    {
        String files = "";
        Path dir = Paths.get(".");
        try {
            DirectoryStream<Path> stream =
            Files.newDirectoryStream(dir);
            for (Path file: stream) {
                files = files + file.getFileName() +"\n";
            }
        } catch (IOException | DirectoryIteratorException x) {
            System.err.println("returnDirectoryList "+x.toString());
        }
        return files;        
    }
}

4 Answers 4

9

Sorry, I don't speak english, it's my first answer. Try to wait the server response:

   do{
        System.out.print("Text to the server? ");
        datakb = kbreader.readLine();
        writer.write(datakb);
        writer.newLine();
        writer.flush();

        System.out.print("Received from the Server:  ");

        DataInputStream dataInputStream = new DataInputStream(client.getInputStream());

        int attempts = 0;
        while(dataInputStream.available() == 0 && attempts < 1000)
        {
            attempts++;
            Thread.sleep(10)
        }

        reader = new BufferedReader(dataInputStream);
        line = reader.readLine();

        while (line.equals("")==false){
            System.out.println(line);
            line = reader.readLine();
        }
   } while (datakb.trim().equals("QUIT")==false);          
   client.close();
   System.exit(0);

  }catch(Exception e){
      System.err.println("Exception: " + e.toString());
  }
  ...
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is because client is missing a empty line while reading LIST output from server. Because of this after LIST command, Server and Client becoming out of sync.

In client code add these two lines end of do while loop. do {

if (datakb.equals("LIST"))
        reader.readLine();
}while( ..)

It should have read the missed line and the problem should go away.

Comments

1

You send all commands to the server and your server only looks for "LIST" as a special command, everything else will be handled by the "echo" part.

if (data == null) {
  continue;
}
if (data.equals("LIST")) {
  writer.write(mycount + "\n" + "150 - Transfer Initiated." + "\n" +
    "DATA " + returnDirectoryList().getBytes().length + "\n" +
    returnDirectoryList() + "\r\n");
} else {
  writer.write("Server Echos to " + mycount + ":" + data + "\n" + "This is a new line." + "\r\n");
}

I tried with your code and the small changes above (since I got NPE) and the output looks like

SERVERSIDE:

Server waiting for client on port 7777
New connection accepted /127.0.0.1: 52889
Received from 1:peter  
Received from 1:LIST

CLIENT SIDE:

Connected to server localhost/127.0.0.1: 7777
local port is 52889
Text to the server? peter
Received from the Server:  Server Echos to 1:peter
This is a new line.
Text to the server? LIST
Received from the Server:  1
150 - Transfer Initiated.
DATA 6
Files
Text to the server? 

Isn't that the expected behaviour?

1 Comment

hello peter i want the server to continue processing requests from client until the client sends QUIT. The main issue is on the client side when the client reads the request from the server. For request except for QUIT that is sent from client the client reads "" from the server.
-1

The statement System.exit(0); in clientThread's run method is the problem.

It is causing the system to exit after serving one client.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.