SagittariusA
SagittariusA

Reputation: 5427

BufferedReader from server does not work

In this code I can correctly receive a request using BufferedReader inClient, created on the client socket. Then I send the request to the server and I see the server gets it. But then, when I try to read the reply from the server (using BufferedReader inServer on the socket of the server), it always ends in IOException: Impossible read from server.

I am referring to the block ################ Do you know any possible reasons?

import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class ProxyMain {

public static void main(String argv[]) {

    int proxyPort = 55554;
    String proxyAddr = "127.0.0.1";
    ServerSocket proxySocket = null;

    try {
        proxySocket = new ServerSocket(proxyPort, 50, InetAddress.getByName("127.0.0.1"));
    }

    catch (Exception e) {
        System.err.println("Impossible to create socket server!");
        System.out.flush();
        System.exit(1);
    }

    System.out.printf("Proxy active on port: %d and on address %s\n", proxyPort, proxySocket.getInetAddress());
    System.out.println();

    while (true) {
        Socket client = null;
        Socket sockServ = null;
        BufferedReader inClient = null;
        PrintWriter outClient = null;
        BufferedReader inServer = null;
        PrintWriter outServer = null;
        String request = new String();
        String tmp = new String();
        String reply = new String();
        String tmpReply = new String();


        try {
            client = proxySocket.accept();
            System.out.println("Connected to: ");
            System.out.println(client.getInetAddress().toString());
            System.out.printf("On port %d\n", client.getPort());
            System.out.println();
            inClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
            outClient = new PrintWriter(client.getOutputStream(), true);

        }

        /*catch (IOException e) {
            System.err.println("Couldn't get I/O for connection accepted");
            System.exit(1);
        }*/

        catch (Exception e) {
            System.out.println("Error occurred!");
            System.exit(1);
        }

        System.out.println("Received request:");

        try{
            for (int i = 0; i<2; i++) {
                tmp = inClient.readLine();
                request = request + tmp;
            }

            inClient.close();
        }
        catch (IOException ioe) {
            System.err.println("Impossible to read mhttp request!");
            System.exit(1);
        }

        System.out.println(request);
        System.out.println();


        try {

            sockServ = new Socket("127.0.0.1", 55555);
            outServer = new PrintWriter(sockServ.getOutputStream(), true);
            inServer = new BufferedReader(new InputStreamReader(sockServ.getInputStream()));

        }

        catch (UnknownHostException e) {
            System.err.println("Don't know about host: 127.0.0.1:55555");
            System.exit(1);
        }

        catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: 127.0.0.1:55555");
            System.exit(1);
        }

        outServer.println(request);
        outServer.close();


        try {
            #################################################
            while ((tmpReply = inServer.readLine()) != null) {
                System.out.println(tmpReply);
                reply = reply + tmpReply;
            }

            inServer.close();
            sockServ.close();

        }

        catch (IOException ioe) {
            System.err.println("Impossible to read from server!");
            System.exit(1);
        }


        outClient.println(reply);
        outClient.close();

        try {
            client.close();
        }

        catch (IOException ioe) {
            System.err.printf("Impossible to close connection with %s:%d\n", client.getInetAddress().toString(), client.getPort());
        }


    }

}

}

UPDATE: It seems that if I do: boolean res = inServer.ready(); it always return false. So Server is not ready to send the reply but this is strange...with my Project in C e Python it worked immediately. Why should java be different?

Upvotes: 0

Views: 276

Answers (2)

xagyg
xagyg

Reputation: 9711

This works, maybe you can get some ideas from it...

ChatServer - broadcasts to all connected clients

In one command prompt: java ChartServer
In another: java ChatClient localhost (or the ip address of where the server is running)
And another: java ChatClient localhost (or the ip address of where the server is running)

Start chatting in the client windows.

Server like this...

// xagyg wrote this, but you can copy it
import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {

    public static List list = new ArrayList();

    public static void main(String[] args) throws Exception {

        ServerSocket svr = new ServerSocket(4444);

        System.out.println("Chat Server started!");

        while (true) {
            try {
                Socket s = svr.accept();
                synchronized(list) {
                   list.add(s);              
                }                                  
                new Handler(s, list).start();
            }
            catch (IOException e) {
                // print out the error, but continue!
                System.err.println(e);
            }
        }
    }
}

class Handler extends Thread {

    private Socket s;
    private String ipaddress;
    private List list;

    Handler (Socket s, List list) throws Exception {
      this.s = s;
      ipaddress = s.getInetAddress().toString();
      this.list = list;
    }

    public void run () {

      try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String message;
        //MyDialog x = (MyDialog)map.get(ipaddress.substring(1));
        while ((message = reader.readLine()) != null) {
            if (message.equals("quit")) {
                synchronized(list) {
                    list.remove(s);
                }
                break;
            }
            synchronized(list) {
                for (Object object: list) {
                    Socket socket = (Socket)object;
                    if (socket==s) continue;
                    PrintWriter writer = new PrintWriter(socket.getOutputStream());
                    writer.println(ipaddress + ": " + message);
                    writer.flush();
                }
            }
        }
        try { reader.close(); } catch (Exception e) {}
      }
      catch (Exception e) {
        System.err.println(e);
      }
    }
}

Client like this ...

// xagyg wrote this, but you can copy it
import java.util.*;
import java.io.*;
import java.net.*;

public class ChatClient {


    public static void main(String[] args) throws Exception {

        Socket s = new Socket(args[0], 4444);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        PrintWriter out = new PrintWriter(s.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String message;
        new SocketReader(in).start();   
        while ((message = reader.readLine())!=null) {
            out.println(message);
            out.flush();
            if (message.equals("quit")) break;
        }
        in.close();
        out.close();
    }        
}

class SocketReader extends Thread {

    BufferedReader in;

    public SocketReader(BufferedReader in) {
        this.in = in;
    }

    public void run() {   
        String message;
        try {
            while ((message = in.readLine())!=null) {
                System.out.println(message);
            }
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }        
    }
}

Upvotes: 0

jtahlborn
jtahlborn

Reputation: 53694

When you close outServer, you close the underlying socket. if you just want to close the output and keep the input open, you need to use Socket.shutdownOutput(). note, you have the same problem when you close inClient.

Upvotes: 1

Related Questions