Hii all, I have already created some programs related to client and server. Today it was my sessional[practical exam] of Client-server technology.
Problem was: i was to add two no's at server sent from client and result back to client.
I tried this solution but some strange solution was there: Server.java
import java.net.*;
import java.io.*;
public class Server{
public static void main(String args[]) throws Exception{
ServerSocket s = new ServerSocket(7896);
Socket cs = s.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(cs.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(cs.getOutputStream()));
bw.write(br.read() + br.read());
}
}
Client.java
import java.io.*;
import java.net.*;
public class Client{
public static void main(String args[]) throws Exception{
Socket s = new Socket("localhost", 7896);
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write(3);
bw.write(4);
System.out.println("Output is: " + br.read());
}
}
when i ran it on dos prompt i got two blank screens; one at client site and one at server site(which was a bit surprising). then i closed server then suddenly i got error msg at client something like connection closed.
Then i ran same program on my ubuntu linux with same jdk 1.6 as it was in windows, and here also blank screens but when i closed server i got:
Output is: -1
Although in exam i done this using DataOutputStream and DataInputStream.
But why the above code is not working.
Can Anyone explain what is happening in the code there.
Thanks
A few comments which might help you reach the correct answer:
accept()
call isn't present in an infinite loop. OuputStream/Writer
to ensure that the data is actually written to the client instead of just lying around in the buffer. BufferedReader
doesn't fetch you the "numbers". But the question is, why flushing is required? To answer this question, one has to understand why "buffering" is used in the first place. Why bother wrapping your streams in another stream when you can directly write to your stream? The reason is that I/O operations are really expensive (at least when compared to accessing your RAM or CPU cache/registers). Frequent writes/reads accessing/writing small chunks of data to the HDD can choke up your HDD and bring down the overall performance of your application.
So what's the solution? Write data to the HDD less frequently. Two ways this can be achieved:
Though the explanation was HDD specific, the same applies to other types of stream like in your case socket.
TL;DR: Buffering improves IO throughput/performance. :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.