Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make client socket wait for data from server socket

Tags:

java

sockets

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;        
    }
}
like image 631
shresthaal Avatar asked Feb 16 '12 04:02

shresthaal


1 Answers

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.

like image 161
Venugopala Krishna Vemula Avatar answered Sep 27 '22 01:09

Venugopala Krishna Vemula