我想从服务器向客户端发送消息,发现几个问题:
- 如果由
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()));