Solved

client/server communication problem with using DataOutputStream

Posted on 2003-10-26
7
360 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

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

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Checkbox and ListView in Android Layout 4 68
Java Jpanels and Jframe 8 33
Which non-HTML GUI front end to use with Java? 3 22
Java: anonymous class 4 23
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
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…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

832 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