?
Solved

client/server communication problem with using DataOutputStream

Posted on 2003-10-26
7
Medium Priority
?
386 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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 

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

Technology Partners: 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!

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn different types of Android Layout and some basics of an Android App.
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month10 days, 10 hours left to enroll

765 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