Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

PrintWriter does not always send (?)

807607Dec 20 2006 — edited Dec 21 2006
Hello!

I've got a problem with my PrintWriter..
or at least I think it is something with the PrintWriter ;)

I have both googled and searched the forum, but found nothing helpfull.

Situation:
I've got a client and a server. sending from client to server works well
but sending from server to client does not. only about the half of my sent
strings get printed out. (Sometimes even less!)

Code (I tried to cut it down a bit, but it is still long, sorry. I hope nothing is missing...):
SERVER:
public class CommandServerBase {
    
    public CommandServerBase() {
        CommandServer l_comServer = new CommandServer();
        l_comServer.start();
    }

    class CommandServer extends Thread {
        ServerSocket serverSocket = null;
        boolean running = true;
        
        CommandServer() {
            System.out.println("setting up command server");
        }
        
        public void run() {
            try {
                serverSocket = new ServerSocket(6682);
            } catch (IOException e) {
                System.err.println("Could not listen on port: 6682.");
            }
            try {
                System.out.println("ready to receive commands");
                while (running)
                    new CommandServerThread(serverSocket.accept()).start();
                serverSocket.close();
            } catch (IOException e) {
                System.err.println("Accept failed.");
            }
        }
        
       class CommandServerThread extends Thread {
            private Socket socket = null;
            private PrintWriter out = null;
            
            public CommandServerThread(Socket socket) {
                super("CommandServerThread");
                this.socket = socket;
            }

           public void run() {
                BufferedReader in = null;
                String inputLine;
                try {
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    out = new PrintWriter(socket.getOutputStream(), true);
                    while ((inputLine = in.readLine()) != null) {
                       sendAnswerToCommandClient(inputLine.trim());
                    }
                } catch (IOException p_oException) {
                    p_oException.printStackTrace();
                }
                finally{
                    System.out.println("closing sockets");
                    try {
                        in.close();
                        out.close();
                        socket.close();
                        System.out.println("socket closed successfully");
                    } catch (IOException p_oException) {
                        p_oException.printStackTrace();
                    }
                }
            }


            private void sendAnswerToCommandClient(String p_strCommand) {
               /* INTERESTING PART */
                sendToCommandClient("aaa");
                sendToCommandClient("bbb");
                sendToCommandClient("ccc");
                sendToCommandClient("ddd");
                sendToCommandClient("eee");
                sendToCommandClient("fff");
                sendToCommandClient("ggg");
                sendToCommandClient("hhh");
                sendToCommandClient("iii");
                sendToCommandClient("jjj");
                sendToCommandClient("kkk");
                sendToCommandClient("lll");
                sendToCommandClient("mmm");
                sendToCommandClient("nnn");
                sendToCommandClient("ooo");
                sendToCommandClient("ppp");
                sendToCommandClient("qqq");
                sendToCommandClient("rrr");
                sendToCommandClient("sss");
                sendToCommandClient("ttt");
                sendToCommandClient("uuu");
                sendToCommandClient("vvv");
                sendToCommandClient("www");
                sendToCommandClient("xxx");
                sendToCommandClient("yyy");
                sendToCommandClient("zzz");
                
                System.out.println("sende EOF");
                sendToCommandClient("EOF"); //yes, ugly, I know. but otherwise it's not shure the client stops reading :(
                sendToCommandClient("EOF"); //*sigh* I really need help, don't I?
                sendToCommandClient("EOF");
                sendToCommandClient("EOF");
                sendToCommandClient("EOF");
                sendToCommandClient("EOF");
                sendToCommandClient("EOF");
            }
            
            private void sendToCommandClient(String str){
                out.println(str);
                out.flush();
            }
        }
    }
}

CLIENT
public class CommandClient {
    
    static Socket kkSocket = null;
    static PrintWriter out = null;
    static BufferedReader in = null;
    static String hostName = "localhost";
    static int port = 6682;
    private boolean m_boIsConnected;
    private BufferedReader l_oBufferedReaderIn;
    private InteractiveFileExecutor m_oInteractiveFileExecutor;
    
    public CommandClient(String[] args) {
        init(args);
        process();
    }
    
    private void process() {
        boolean l_boIsRunning = true;
        while (l_boIsRunning ){

            System.out.println("\n\nLooking for CommandServer at "+hostName+" port "+port+".");
            boolean l_boIsFirstTry = true;
            while (!m_boIsConnected){
                try {
                    if (!l_boIsFirstTry){
                        System.out.print("try to connect again in 10 Sek ...");
                        for (int i = 9; i>=0 ; i--){
                            Thread.sleep(1000);
                            System.out.print("\b\b\b\b\b\b\b\b\b\b");
                            System.out.print(" "+i+" Sek ...");
                        }
                    }
                    l_boIsFirstTry = false;
                    connect();
                    m_boIsConnected= true;
                    System.out.println("\r"+Calendar.getInstance().getTime()+" connected successfully                       ");
                } catch (UnknownHostException p_oException) {
                    System.out.println("!Exception: unknown host!");
                    m_boIsConnected = false;
                } catch (IOException p_oException) {
                    System.out.flush();
                    System.out.print("\r"+Calendar.getInstance().getTime()+" no CommandServer found                                \n");
                    m_boIsConnected = false;
                } catch (InterruptedException p_oException) {
                    p_oException.printStackTrace();
                }
            }
            System.out.println("Ready to send! (Type h to get Help)");
            while (m_boIsConnected ){
                try {
                    String l_strFromUser = "";
                    if (l_oBufferedReaderIn == null){
                        l_oBufferedReaderIn = new BufferedReader(new InputStreamReader(System.in));
                    }
                    while ((l_strFromUser = l_oBufferedReaderIn.readLine()) != null && m_boIsConnected) {
                        l_strFromUser = l_strFromUser.trim();
                        /* send - INTERESTING PART */
                        sendToServer(l_strFromUser);
                        String l_strReply;
                        int l_nNrOfFound = 0;
                        System.out.println("Query started...");
                        while ((l_strReply =in.readLine()) != null && m_boIsConnected){
                            if (l_strReply.equals("EOF")){
                                break;
                            }
                            l_nNrOfFound++;
                            System.out.println(l_strReply);
                        }
                    }
                    if (l_nNrOfFound >0){
                        System.out.println("...finished! "+l_nNrOfFound+" Datapoints found.");
                    } else {
                        System.out.println("no Datapoints found!");
                    }
                } catch (EOFException e) {
                    System.out.println("connection Lost!");
                    m_boIsConnected = false;
                } catch (IOException p_oException) {
                    System.out.println("unknown exception in process");
                    m_boIsConnected = false;
                } catch (NullPointerException p_oException) {
                    m_boIsConnected = false;
                }
            }
        }
    }
    
    public static void main(String[] args){
        new CommandClient(args);
    }

    private void init(String[] p_oArgs){
        if (p_oArgs != null) {
            if (p_oArgs.length > 1) {
                hostName = p_oArgs[0];
                port = Integer.parseInt(p_oArgs[1]);
            }
        }
    }
    
    public void sendToServer(String p_strMessage) throws NullPointerException {
        out.println(p_strMessage);
        out.flush();
        System.out.println("   ---> sent to Server");
    }
    
    public void connectionLost(){
        in = null;
        out = null;
        m_boIsConnected = false;
        if (m_oInteractiveFileExecutor != null){
            if (m_oInteractiveFileExecutor.isAlive()){
                m_oInteractiveFileExecutor.interrupt();
                if (m_oInteractiveFileExecutor.isAlive()){
                    m_oInteractiveFileExecutor.stop();
                }
            }
            
            m_oInteractiveFileExecutor = null;
        }
    }
    private void connect() throws UnknownHostException, IOException {
        if (kkSocket != null){
            kkSocket.close();
        }
        kkSocket = new Socket(hostName, port);
        out = new PrintWriter(kkSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
        new ConnectionWatcher(kkSocket, this).start();
        m_boIsConnected = true;
    }
}
Output in client:
"
Query started...
bbb
ddd
fff
hhh
jjj
lll
nnn
ppp
rrr
ttt
vvv
xxx
zzz
...finished! 13 Datapoints found.
"
As you can see: every second line is missing. Is it something with buffering? but the output would not just disappear then, would it?

I have autoflush on and have also tried to flush manually. (that seems to be the problem in most cases ;p)
can someone give me a hint what my problem might be?

thanks for reading
Sophia

ps: if there is some information missing, please ask! ;)
pps: sorry if the code is ugly. It was something old I had ro extend and I did not rewrite it compleatly..
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 18 2007
Added on Dec 20 2006
6 comments
1,082 views