Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

client/server communication problem with using DataOutputStream

Posted on 2003-10-26
7
Medium Priority
?
390 Views
Last Modified: 2010-05-19
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
Comment
Question by:zhangmu
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 2

Expert Comment

by:f_98
ID: 9622872
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
 
LVL 86

Accepted Solution

by:
CEHJ earned 580 total points
ID: 9622977
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 9623920
:-)
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:zhangmu
ID: 9626147
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
 
LVL 2

Expert Comment

by:f_98
ID: 9626874
just a hunch, but try putting another \n on the client's

      outToServer.writeBytes("ok\n");

0
 
LVL 2

Expert Comment

by:f_98
ID: 9626895
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
 

Author Comment

by:zhangmu
ID: 9630920
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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question