本文介绍了java中的BufferedWriter和socket,write没有作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个小型客户端应用程序来与服务器进行通信.我在我的客户端和服务器之间打开一个套接字,并且可以使用 BufferedReader 读取从服务器发出的任何内容.这是在一个线程中读取的.但是,当我使用 BufferedReader 在套接字上写入时,没有任何反应!没有例外,但没有任何服务器响应(它应该有一个服务器响应)这是我的代码:

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 with a BufferedReader. This is read in a thread. However, when I write on the socket using a BufferedReader, nothing happens ! No exception but not any server response (and it should have a server response)Here is my code:

socketWritter.write(message);
socketWritter.write("
");
System.out.println(socketWritter.toString());
socketWritter.flush();

我的套接字正确打开并且 mu BufferedWriter 正确初始化:

My socket is correctly open and mu BufferedWriter correctly initialized :

new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))

我不知道为什么这不起作用??任何帮助都会很棒!问候

I have no idea why this doesn't work ??Any help would be great !Regards

推荐答案

您的代码是正确的.我使用通用服务器对其进行了测试,该服务器将回显客户端发送的任何内容,并且运行良好(没有任何更改).可能是您使用的服务器有问题.我注意到的一件事是,对于我的服务器,我需要在每次写入输出流时附加一个新行字符,以便它实际发送数据.我敢打赌这就是你的 GUI 没有收到任何东西的原因.这是来自我的服务器的客户端线程类:

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();
            }

        }
    }

}

这篇关于java中的BufferedWriter和socket,write没有作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 12:48