I want to send a message from the server to the client and found several problems:
- if sent by
out.flush(); method then the client can read it, but - when I use the method
out.write();then the client receives the status of-1(not receiving data)
What should I add so that the client can receive messages with the method in nmbr 2. The following is the method I use on the client side to receive the message from server:
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();
at client side i use this:
DataInputStream in = new DataInputStream(clientsock.getInputStream());
DataOutputStream out = new DataOutputStream(clientsock.getOutputStream());
at server side i use this:
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(
new OutputStreamWriter(socket.getOutputStream()));
try this:
and then use out.println() to send a line across?
By default print streams dont flush() after write() calls due to performance reasons.
So if you dont want to have to use flush directly you have to use one of the following “println, printf, or format ” plus the constructor that enables auto flushing
http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html