sqtd
sqtd

Reputation: 505

Client server communication java

I have a problem in a client-server application. The client sends a picture to the server and the server responds with a reply message.

Here is my server code:

public class Server
{
    public static void main(String[] args) throws Exception
    {
        String response="response";
        ServerSocket socket = new ServerSocket(3333);
        while (true)
        {
            Socket clientSocket = socket.accept();

            DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
            FileOutputStream fout = new FileOutputStream("output.jpg");
            int i;
            while ( (i = dis.read()) > -1) 
                fout.write(i);    

            DataOutputStream outToClient= new    DataOutputStream(clientSocket.getOutputStream());

            outToClient.writeBytes(response);

            fout.flush();
            fout.close();
            dis.close();
            outToClient.close();
            clientSocket.close();
        }
    }
}

Client:

public static void main(String[] args) throws Exception
{
    // TODO Auto-generated method stub
    String sentence;
    int i;
    FileInputStream fis = new FileInputStream ("pathphoto.jpg");   
    Socket sock = new Socket ("hostname",3333);
    DataOutputStream os = new DataOutputStream(sock.getOutputStream());
    System.out.println("Sending....");
    while ((i = fis.read()) > -1)
        os.write(i);

    BufferedReader inFromServer= new BufferedReader(new InputStreamReader(sock.getInputStream()));
    sentence=inFromServer.readLine();
    System.out.println("FROM SERVER: " + sentence);
    fis.close();
    os.close();
    sock.close();
}
}

The problem is that the client doesn't receive the response from the server and I think along these lines:

BufferedReader inFromServer= new BufferedReader(new InputStreamReader(sock.getInputStream()));
sentence=inFromServer.readLine();

Because without them the server sends the response.

Any advice on how to fix it?

Upvotes: 1

Views: 990

Answers (1)

Rohit
Rohit

Reputation: 525

Its not stuck in BufferedReader, it is actually stuck in while ((i = fis.read()) > -1) Since your client never told server length of stream, or closed stream server will try to read next byte from inputstream and will be stuck when client is done sending file and waiting for response from server.

When you remove code to read response back from server, client goes ahead and closes all streams and in that case server reads a -1 and goes ahead.

Upvotes: 1

Related Questions