BufferedWriter and socket in java, write has no effect

后端 未结 3 2075
余生分开走
余生分开走 2021-01-07 05:28

I\'m writing a small client application to communicate with a server. I open a socket between my client and the server and can read anything that goes out from the server wi

相关标签:
3条回答
  • 2021-01-07 05:30

    At this point, there is no convincing evidence that your client code is not working. In particular, this statement:

    System.out.println(socketWritter.toString());
    

    won't tell you anything useful. The toString() method only on a Stream object most likely only tells you the object's class name and its identity hashcode. It certainly won't tell you what you've written to the stream.

    Given that, there is no clear evidence that the flush hasn't worked. (The problem could be on the server side.)

    0 讨论(0)
  • 2021-01-07 05:30

    Use only OutputStreamWriter without BufferedWriter and use flush()

    0 讨论(0)
  • 2021-01-07 05:50

    Your code is correct. I tested it with a generic server that will echo whatever the client sends and it worked fine (with no changes). It could be that the server your using is faulty. One thing I noticed was that for my server I needed to append a new line character every time I wrote to the output stream, for it to actually send the data. I'm willing to bet that's why your GUI isn't receiving anything. Here's the client thread class from my server:

    class ClientThread extends Thread {
    
        private Socket          sock;
        private InputStream     in;
        private OutputStream    out;
    
        ClientThread( Socket sock ) {
            this.sock = sock;
            try {
                this.in = sock.getInputStream();
                this.out = sock.getOutputStream();
            } catch ( IOException e ) {
                e.printStackTrace();
            }
        }
    
        //Echos whatever the client sends to it
        public void run() {
            BufferedReader bufIn = new BufferedReader( new InputStreamReader( in ) );
            BufferedWriter bufOut = new BufferedWriter( new OutputStreamWriter( out ) );
            while ( true ) {
                try {
                    String msg = bufIn.readLine();
                    System.out.println( "Received: " + msg );
                    bufOut.write( msg );
                    bufOut.newLine(); //HERE!!!!!!
                    bufOut.flush();
                } catch ( IOException e ) {
                    e.printStackTrace();
                }
    
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题