• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 393
  • Last Modified:

client/server communication problem with using DataOutputStream

I am currently writing a client server application in java. so client request a file name to server, server then search through its currently located folder to see if the file exsits. if yes, server send a message to client says file found, then client send back "ok", then server output the answer from the client which is "ok". otherwise, server send "file not found" to client. the problem I had was that when server found the file and send "file found" to client, client having problem with send back "ok" by using DataOutputStream. could any expert please help me. thanks.

this is the code from client:
import java.io.*;
import java.net.*;
public class TCPfileClient
{
  public static void main(String argv[]) throws Exception
  {
    String filename;
    String result;
    String hostName;
    BufferedReader inputFromUser = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Please enter the host name:");
    hostName=inputFromUser.readLine();
    System.out.println("Create the client socket");
    Socket clientSocket = new Socket(hostName, 6789);

    System.out.println("Attach an output stream to the socket");

    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
    System.out.println("Attach an input stream from the socket");
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    System.out.println("Implement the functionality");
    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("What file are you looking for?");
    filename = inFromUser.readLine();
    outToServer.writeBytes(filename + '\n');

    result = inFromServer.readLine();
    if (result.equalsIgnoreCase("file found"))
    {
      System.out.println("Searching result: " + result);
      outToServer.writeBytes("ok");
    }

    else
    {
      System.out.println(result);
    }

    System.out.println("Close the socket");
    clientSocket.close();
  }
}



this is the code from server:
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPfileServer
{
  public static void main(String argv[]) throws Exception
  {
    int clientID = 0;
    System.out.println("Create the welcoming socket");
    ServerSocket welcomeSocket = new ServerSocket(6789);
    while(true)
    {
      System.out.println("Waiting for client request");
      Socket connectionSocket = welcomeSocket.accept();
      clientID++;
      System.out.println("Socket for Client " + clientID + " is created");
      new ServerThread(connectionSocket, clientID);
    }
  }
}

class ServerThread extends Thread
{
  int clientID;
  Socket socket;
  public ServerThread(Socket s, int client)
  {
    socket = s;
    clientID = client;
    start();
  }
  public void run()
  {
    try
    {
      System.out.println("Attach an output stream to socket of Client " + clientID);
      PrintWriter o=new PrintWriter(socket.getOutputStream());
      DataOutputStream  outToClient = new DataOutputStream(socket.getOutputStream());
      System.out.println("Attach an input stream to socket of Client " + clientID);
      BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      String clientSentence;

      clientSentence = inFromClient.readLine();
      System.out.println("Searching file for Client " + clientID);
      File target=new File(clientSentence);
      File target2=target.getAbsoluteFile();
      String m="ok";
      if (target.exists())
      {

        outToClient.writeBytes("file found");
        System.out.println(clientSentence);

      }
      else
      {
        outToClient.writeBytes("File not found");


      }
      System.out.println("Socket for Client " + clientID + " is closed");
      outToClient.close();
      socket.close();
    }
    catch (IOException e)
    {
      System.err.println(e.toString());
    }
  }
}

0
zhangmu
Asked:
zhangmu
  • 3
  • 2
  • 2
1 Solution
 
f_98Commented:
try adding \n to the response (since ur using readLine())
then make sure you read back the "ok" response before you close the connection

      if (target.exists())
      {
        outToClient.writeBytes("file found\n");
        System.out.println(clientSentence);

      }
      else
      {
        outToClient.writeBytes("File not found");
      }

        // probably another read here for the response
0
 
CEHJCommented:
There's no need for the specialised stream class DataOutputStream that I can see. Simply use a PrintWriter:

PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

then you can do:

outToServer.println("ok");

which will solve your problem
0
 
CEHJCommented:
:-)
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
zhangmuAuthor Commented:
thanks for the help, but now I have modified the code so that it can transfer file. and simpliar problem happened again, when client send out the correct file name, and the server send back "file found", then both program just stay running and no result coming out. which seems the file content couldnt been transfer.

this is the code from the server:
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPfileServer
{
  public static void main(String argv[]) throws Exception
  {
    int clientID = 0;
    System.out.println("Create the welcoming socket");
    ServerSocket welcomeSocket = new ServerSocket(6789);
    while(true)
    {
      System.out.println("Waiting for client request");
      Socket connectionSocket = welcomeSocket.accept();
      clientID++;
      System.out.println("Socket for Client " + clientID + " is created");
      new ServerThread(connectionSocket, clientID);
    }
  }
}

class ServerThread extends Thread
{
  int clientID;
  Socket socket;
  public ServerThread(Socket s, int client)
  {
    socket = s;
    clientID = client;
    start();
  }
  public void run()
  {
    try
    {
      System.out.println("Attach an output stream to socket of Client " + clientID);
      DataOutputStream  outToClient = new DataOutputStream(socket.getOutputStream());
      System.out.println("Attach an input stream to socket of Client " + clientID);
      BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      String clientSentence;
      clientSentence = inFromClient.readLine();
      System.out.println("Searching file for Client " + clientID);
      File target=new File(clientSentence);
      File target2=target.getAbsoluteFile();
      String m="ok";
      if (target.exists())
      {
        outToClient.writeBytes("file found\n");
        String incom;
        incom=inFromClient.readLine();
        if (incom.equalsIgnoreCase(m))
        {
        System.out.println("correct");
        try
        {
          byte[] buf = new byte[1024];

          BufferedOutputStream out = new BufferedOutputStream(outToClient,1024);
          BufferedInputStream bis=new BufferedInputStream(new FileInputStream(target2));
          int i;
          int bytecount=1024;
          while ( (i = bis.read(buf,0,1024)) != -1)
          {
            bytecount=bytecount+1024;
            out.write(buf,0,1024);
            out.flush();
          }
          out.close();
          bis.close();
          System.out.println("Bytes Sent :"+bytecount);
        }
        catch (IOException e)
        {
          System.out.println(e);
        }
      }
    }
    else
    {
      outToClient.writeBytes("File not found");
    }
    System.out.println("Socket for Client " + clientID + " is closed");
    outToClient.close();
    socket.close();
    }
    catch (IOException e)
    {
      System.err.println(e.toString());
    }
  }
}



this is the code from client:
import java.io.*;
import java.net.*;
public class TCPfileClient
{
  public static void main(String argv[]) throws Exception
  {
    String filename;
    String result;
    String hostName;
    BufferedReader inputFromUser = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Please enter the host name:");
    hostName=inputFromUser.readLine();
    System.out.println("Create the client socket");
    Socket clientSocket = new Socket(hostName, 6789);
    System.out.println("Attach an output stream to the socket");
    DataInputStream is = new DataInputStream(clientSocket.getInputStream());
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
    System.out.println("Attach an input stream from the socket");
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(is));
    System.out.println("Implement the functionality");
    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("What file are you looking for?");
    filename = inFromUser.readLine();
    outToServer.writeBytes(filename + '\n');
    result = inFromServer.readLine();
    if (result.equalsIgnoreCase("file found"))
    {
      System.out.println("Searching result: " + result);
      outToServer.writeBytes("ok");
     try
      {
        byte[] bytes = new byte[1024];
        int len=0;
        int bytcount = 1024;
        File f=new File("test.txt");
        BufferedInputStream in2 = new BufferedInputStream(is, 1024);
        FileOutputStream inFile= new FileOutputStream(f);
        while ( (len = in2.read(bytes, 0, 1024)) != -1)
        {
          bytcount = bytcount + 1024;
          inFile.write(bytes, 0, 1024);
        }
        inFromServer.close();
        inFile.close();
        in2.close();
        System.out.println("Bytes Sent :"+bytcount);
        is.close();
      }
      catch(IOException e)
      {
        System.out.println("Unable to open file" + e);
        return;
      }
     }
   else
   {
      System.out.println(result);
   }
    System.out.println("Close the socket");
    clientSocket.close();
  }
}
0
 
f_98Commented:
just a hunch, but try putting another \n on the client's

      outToServer.writeBytes("ok\n");

0
 
f_98Commented:
clarification, just put one "\n", should work because you are using readline() and that never stops expecting characters until it encounters a line terminator
0
 
zhangmuAuthor Commented:
thanks to f_98 very much. I have been thinking what was going on for a couple of days, but finally you have solved my problem. I am just started to learn network programming in java, so I am not very clear about the use of those stream classes. but thank you for the help.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now