1

When I run this program the Client class prompts the user to enter a command, and that command should go to the Server class and open a file and read each line of that file and return the byte length back to the Client class to be displayed.

Unfortunately once i enter the command, nothing happens & Not sure why.

TCP Client Class

package TcpClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.io.*;

public class TcpClient {
  public static void main(String[] args) {
    String temp;
    String displayBytes;
    try {
      //create input stream
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
      //create client socket, connect to server
      Socket clientSocket = new Socket("localhost",5555);
      //create output stream attached to socket
      DataOutputStream outToServer =
      new DataOutputStream(clientSocket.getOutputStream());

      System.out.print("Command : ");

      //create input stream attached to socket
      BufferedReader inFromServer =
      new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      temp = inFromUser.readLine();

      //send line to server
      outToServer.writeBytes(temp);

      //read line from server
      //displayBytes = inFromServer.readLine();

      while((displayBytes = inFromServer.readLine()) != null) {
        System.out.print(displayBytes);
      }
      //clientSocket.close();
    }
    catch(Exception ex) {
    }
  }
}

TCP Server Class

package TcpServer;

import java.io.BufferedReader;
import java.io.*;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
  public static void main(String[] args) {
    // The name of the file to open.
    String fileName = "input.txt";
    // This will reference one line at a time
    String line = null;
    String holder=null;
    String clientWord;
    int bytNumber;

    try {
      //create welcoming socket at port 5555
      ServerSocket welcomeSocket = new ServerSocket(5555);
      //wait, on welcoming socket for contact by client
      Socket connectionSocket = welcomeSocket.accept();
      //create input stream, attached to socket
      BufferedReader inFromClient = 
      new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
      //create output stream, attached to socket
      DataOutputStream outToClient =
      new DataOutputStream(connectionSocket.getOutputStream());
      //read in line from socket
      clientWord = inFromClient.readLine();

      if(clientWord.equals("query")) {
        try {
          // FileReader reads text files in the default encoding.
          FileReader fileReader = new FileReader(fileName);

          // Always wrap FileReader in BufferedReader.
          BufferedReader buffer = new BufferedReader(fileReader);

          while((line = buffer.readLine()) != null) {
            System.out.println(line);
            bytNumber = line.getBytes().length;
            holder=Integer.toString(bytNumber);
            //pr.println(bytNumber);//only printing first line not going until eof
            outToClient.writeBytes(holder);
            // line = buffer.readLine();
            // pr.flush();
          }   

          // Always close files.
          buffer.close();         
        }
        catch(FileNotFoundException ex) {
          System.out.println("Unable to open file '" + fileName + "'");
        }
        catch(IOException ex) {
          System.out.println ("Error reading file '" + fileName + "'");
          // Or we could just do this: 
          // ex.printStackTrace();
        }
      }// end if statement
    }
    catch(Exception ex) {
    }
  }
}
4
  • 1
    You would start by not ignoring exceptions in your client class. You see, ignoring error messages isnt exactly a good way of debugging ... Commented Oct 6, 2016 at 19:07
  • The only message I get is a warning to close clientSocket but when i did that I still get the same output. Commented Oct 6, 2016 at 19:13
  • There can be various problems, like not properly closing sockets here or there, or connectivity issues, ... so, hint: try to run things in a debugger. Add print statements to see what is going on; and maybe first of all: read step by step tutorials (like docs.oracle.com/javase/tutorial/networking/sockets/… ) that guide you through the whole process of client/server communication. Commented Oct 6, 2016 at 19:17
  • 2
    @n00bie1221 How ironic that one of your catch blocks contains the comment "or we could just do this: ex.printStackTrace();" yet you choose not to do it, which is the worst mistake in the code you've shown. Commented Oct 6, 2016 at 19:28

1 Answer 1

7

I suggest you to only DataOutputStream and DataInputStream in both sides and to not use BufferedInputStream. The slightly modified code below is able to correctly send the message from the client to the server. Now you can easily make it work for what you want to achieve.

Server

import java.io.BufferedReader;
import java.io.*;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;



public class TcpServer {


public static void main(String[] args) {
    // The name of the file to open.
    String fileName = "input.txt";
    // This will reference one line at a time
    String line = null;
    String holder=null;
    String clientWord;
    int bytNumber;

    try
    {
        //create welcoming socket at port 5555
        ServerSocket welcomeSocket = new ServerSocket(5555);
        //wait, on welcoming socket for contact by client
        Socket connectionSocket = welcomeSocket.accept();
        //create input stream, attached to socket
        DataInputStream inFromClient =
                new DataInputStream(connectionSocket.getInputStream());
        //create output stream, attached to socket
        DataOutputStream outToClient =
                new DataOutputStream(connectionSocket.getOutputStream());
        //read in line from socket
        clientWord = inFromClient.readUTF();
    System.out.println(clientWord);

        if(clientWord.equals("query"))
        {


            try 
            {
         // FileReader reads text files in the default encoding.
         FileReader fileReader = new FileReader(fileName);


         // Always wrap FileReader in BufferedReader.
         BufferedReader buffer = new BufferedReader(fileReader);


                while((line = buffer.readLine()) != null) 
                {
             System.out.println(line);
             bytNumber = line.getBytes().length;
             holder=Integer.toString(bytNumber);
             //pr.println(bytNumber);//only printing first line not going until eof
            outToClient.writeBytes(holder);
             // line = buffer.readLine();
            // pr.flush();
                }   

         // Always close files.
         buffer.close();         
            }
            catch(FileNotFoundException ex) 
            {
         System.out.println(
             "Unable to open file '" + 
             fileName + "'");                
            }
            catch(IOException ex) 
            {
         System.out.println(
             "Error reading file '" 
             + fileName + "'");                  
         // Or we could just do this: 
         // ex.printStackTrace();
            }

        }// end if statement
    }

  catch(Exception ex)
    {

    }
}

}

Client

import java.io.BufferedReader;
  import java.io.InputStreamReader;
  import java.net.Socket;
  import java.io.*;


  public class TcpClient {


       public static void main(String[] args) {
         String temp;
         String displayBytes;
        try
        {
        //create input stream
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        //create client socket, connect to server
        Socket clientSocket = new Socket("localhost",5555);
        //create output stream attached to socket
        DataOutputStream outToServer =
                new DataOutputStream(clientSocket.getOutputStream());



        System.out.print("Command : ");

        //create input stream attached to socket
        DataInputStream inFromServer = new DataInputStream(clientSocket.getInputStream());

        temp = inFromUser.readLine();

        //send line to server
        //outToServer.writeBytes(temp);
        outToServer.writeUTF(temp);
        outToServer.flush();


       //read line from server
        //displayBytes = inFromServer.readLine();

        while((displayBytes = inFromServer.readUTF()) != null)
        {
        System.out.print(displayBytes);
        }
        //clientSocket.close();
    }
    catch(Exception ex)
    {

    }
}
}
Sign up to request clarification or add additional context in comments.

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.