BufferedWriter和socket中的java,写没有效果 [英] BufferedWriter and socket in java, write has no effect

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

问题描述

我正在编写一个小型客户端应用程序来与服务器通信。我在客户端和服务器之间打开一个套接字,可以使用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("\n");
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();
            }

        }
    }

}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆