I'm trying to do some Socket programming in Java, and I'm using the BufferedStreamReader.read(char[]) method.
the java doc states:
Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
Only it's not blocking on input.
can somone point out the problem with the following code? Even with the line that writes to the output stream the line that prints "RCVD:" is printing but without any data after the RCVD.
public class Main {
/**
* @param args the command line arguments
*/
private static Socket tcpSocket;
public static void main(String args[]) {
try {
tcpSocket = new Socket("localhost", 8080);
} catch (UnknownHostException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
new Thread(new Runnable() {
public void run() {
try {
System.out.println("Starting listening");
char[] dataBytes = new char[9];
BufferedReader netStream = new BufferedReader(new InputStreamReader(tcpSocket.getInputStream()));
while (true) {
netStream.read(dataBytes);
System.out.println("RCVD: " + String.copyValueOf(dataBytes));
}
} catch (UnknownHostException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
new Thread(new Runnable(){
public void run() {
System.out.println("Starting Writer");
PrintWriter out = null;
try {
out = new PrintWriter(tcpSocket.getOutputStream(), true);
for (int i = 0 ; i < 10 ; i++)
{
// out.println("000000000");
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
}
}
ADDITIONAL INFO
I've tried changing the port number and the application crashes, maybe I'm connecting to something else running on the machine.
Also I am reciveing a steady stream of bytes all of which are spaces by the looks of it.