Solved

client/server communication problem with using DataOutputStream

Posted on 2003-10-26
7
347 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
  • 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 145 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

929 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now