I have a stream that reads characters from a buffered reader (created from a socket as follows):
inputStream = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
This code only works once. For example, if a client connects and sends this message: “This is a test” and “This is another test”, the output of the host:
Reading from stream: Chars read from stream: 16 This is a test Reading from stream:
Please note that the program does not get “This is another test” because it gets stuck while reading the stream. Is there a way to handle this without decreasing the size of the buffer? This is the code for the stream:
public void run() { boolean dataRecieved = false; char[] inputChars = new char[1024]; int charsRead = 0; while (!stopNow) { try { Thread.sleep(getDataDelay);
Code for client / sender (not my code):
public static void main(String[] args) throws IOException { // <<<<<<<<<<< CLIENT >>>>>>>>>>>>>>> Socket sock = new Socket("127.0.0.1", 3000); // reading from keyboard (keyRead object) BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in)); // sending to client (pwrite object) OutputStream ostream = sock.getOutputStream(); PrintWriter pwrite = new PrintWriter(ostream, true); // receiving from server ( receiveRead object) InputStream istream = sock.getInputStream(); BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream)); System.out.println("Start the chitchat, type and press Enter key"); String receiveMessage, sendMessage; while(true) { sendMessage = keyRead.readLine(); // keyboard reading pwrite.println(sendMessage); // sending to server System.out.flush(); // flush the data if((receiveMessage = receiveRead.readLine()) != null) //receive from server { System.out.println(receiveMessage); // displaying at DOS prompt } } }
David
source share