【问题标题】:problems in the method out.write ();out.write() 方法中的问题;
【发布时间】:2012-05-19 21:07:51
【问题描述】:

我想从服务器向客户端发送消息,发现几个问题:

  • 如果由out.flush() 发送;方法然后客户端可以读取它,但是
  • 当我使用out.write();方法时,客户端收到-1的状态(未接收数据)

我应该添加什么,以便客户端可以使用 nmbr 2 中的方法接收消息。以下是我在客户端用于从服务器接收消息的方法:

    int totalBytesRcvd = 0; // Total bytes received
    int bytesRcvd; // Bytes received in last read
    byte[] byteBufferreceive = new byte[256];
    while (totalBytesRcvd < byteBufferreceive.length) {
        if ((bytesRcvd = in.read(byteBufferreceive, totalBytesRcvd, 
    byteBufferreceive.length - totalBytesRcvd)) == -1)
        {
        Toast.makeText(this, "byte lenght: "+bytesRcvd, Toast.LENGTH_SHORT).show();
        Toast.makeText(this, "communication error", Toast.LENGTH_LONG).show();
        }
        totalBytesRcvd += bytesRcvd;            
    }
    System.out.println("The length of the received data "+totalBytesRcvd);
    String receive;
    receive = new String(byteBufferreceive);
    Toast.makeText(this, receive, Toast.LENGTH_LONG).show(); 

在客户端我使用这个:

    DataInputStream in = new DataInputStream(clientsock.getInputStream());

    DataOutputStream out = new DataOutputStream(clientsock.getOutputStream());

在服务器端我使用这个:

        in  = new BufferedReader(
              new InputStreamReader(socket.getInputStream()));

        out = new PrintWriter(
              new OutputStreamWriter(socket.getOutputStream()));

【问题讨论】:

  • 您使用什么类型的流进行输入/输出?
  • @skaffman 我在上面添加了
  • @OsamaJaved 我在上面添加了

标签: java sockets io


【解决方案1】:

试试这个:

out = new PrintWriter(socket.getOutpustStream(),true)

然后使用 out.println() 发送一行?

由于性能原因,默认情况下打印流不会在 write() 调用后刷新()。

因此,如果您不想直接使用刷新,则必须使用以下“println、printf 或格式”之一以及启用自动刷新的构造函数

http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html

【讨论】:

  • 我不久前做的一个项目的这个工人。我在服务器端启用了自动刷新并在客户端使用了 bufferedReader。
  • 在构造函数中,将 autoflushing 设置为 true。请注意上面构造中的第二个参数,并查看上面的链接以获取更多信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
相关资源
最近更新 更多