BufferedWriter.write()似乎不起作用

时间:2012-10-16 14:51:18

标签: java android sockets bufferedwriter

我有两个Java应用程序,其中Android客户端连接到计算机上的服务器,并使用BufferedWriter通过websockets发送消息。

客户:

    try {
        toast("Sending...");
        Socket sock = new Socket(ip, PORT);
        OutputStream os = sock.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
        bw.flush();
        bw.write("Hello Server!");
        toast("Connected!");
    } catch (UnknownHostException e) {
        toast(e.getMessage());
    } catch (IOException e) {
        toast(e.getMessage());
    }

服务器:

public static void main(String[] args) {
    ServerSocket server;
    ConnectionThread ct;
    Socket s;
    ExecutorService es = Executors.newSingleThreadExecutor();
    try {
        System.out.println("Starting server...");
        server = new ServerSocket(1337);
        s = server.accept();
        ct = new ConnectionThread(s);
        es.execute(ct);
    } catch (IOException ex) {
        ex.printStackTrace();
    }       
}

ConnectionThread类:

public class ConnectionThread implements Runnable {
    private Socket sock;
    private InputStream is;
    private BufferedReader br;
    private boolean online;
    public ConnectionThread(Socket s) {
        System.out.println("Creating connection thread.");
        this.sock = s;
        online = true;
    }
    @Override
    public void run() {
        String input = "";
        try {
            System.out.println("Starting to read...");
            is = sock.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));

            while (online) {
                input = br.readLine();
                if(input != null){
                    System.out.print("Received message: ");
                    System.out.println(input);
                }

            }

            br.close();
            is.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

当我运行服务器,然后运行客户端时,客户端将显示"已连接!" toast,服务器的输出将是:

Starting server...
Creating connection thread.
Starting to read...

因此,似乎实际上正在建立连接,但消息未到达。有谁知道为什么会发生这种情况?

3 个答案:

答案 0 :(得分:4)

您的服务器期望换行符终止整行。尝试:

bw.write("Hello Server!");
bw.newLine();

答案 1 :(得分:0)

这样做......

String s = new String();

while ((br.readLine())!=null) {

                s = s+br.readLine();

                    System.out.print("Received message: ");
                    System.out.println(input);
                }

            }

     bw.println("Hello Server");

答案 2 :(得分:0)

我注意到你没有在你的客户端上发送一个结束,所以BufferedReader.readline()永远不会返回,因为它不能匹配\ n字符。再次尝试使用

        bw.write("Hello Server!\n");

在客户端。