MyWriter.java (execute this before MyReader.java)
import java.io.*;
import java.net.*;
import java.util.* ;
public class MyWriter {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(1234) ;
System.out.println("Server started...\n\n") ;
Socket s = ss.accept() ;
OutputStream out = s.getOutputStream() ;
Scanner scan = new Scanner(System.in) ;
while(true){
System.out.print("Enter integer (or something else to quit) : ");
try{
int i = scan.nextInt() ;
out.write(i) ;
}catch(RuntimeException rte){
System.out.println("\n\n") ;
rte.printStackTrace() ;
System.out.println("\n\n") ;
break ;
}
}
}
}
MyReader.java (only executed, when done with MyWriter.java)
import java.io.*;
import java.net.*;
import java.util.* ;
public class MyReader {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 1234) ;
InputStream is = s.getInputStream() ;
int i ;
while( (i = is.read()) != -1 ){
System.out.println( "character form : " + (char)i + ", int form : " + i);
}
}
}
Problem : MyReader is not getting terminated, even if I am passing -1 in MyWriter.
Read returns an
intso that it can also indicate the end of the stream, as -1. If the signature werethen you’d never know when the stream had ended (unless it threw an exception, I suppose).
I suspect there’s no particular reason for
writeto take anint– it seems a slightly strange choice to me. The Javadoc specifically says that the higher 24 bits are ignored. Maybe this is just an accident of history.(In .NET,
Stream.ReadBytereturns anint, butStream.WriteBytetakes abyte. This makes more sense IMO.)Now, with that background, when you write “-1” to your stream, you’re actually writing the value “255” – and that’s what you read back. “-1” is represented in binary as “all 1s” so the lower 8 bits of that are “11111111” which is 255 when considered as an unsigned value.
Your reader will only terminate when you close the output stream in the “writing” application – because that’s when
read()will return -1.