我想从服务器向客户端发送消息,发现了几个问题:
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()));
答案 0 :(得分:0)
试试这个:
out = new PrintWriter(socket.getOutpustStream(),true)
然后使用out.println()发送一行?
默认情况下,由于性能原因,在write()调用之后,打印流不会刷新()。
因此,如果您不想直接使用flush,则必须使用以下“println,printf或format”之一以及启用自动刷新的构造函数
http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html