-
Java Socket Issue!
Hi,
EchoClient class creates a socket thereby getting a connection to the Echo server. It reads input from the user on the standard input stream, and then forwards that text to the Echo server by writing the text to the socket. The server echoes the input back through the socket to the client. The client program reads and displays the data passed back to it from the server.
Code:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
I have edited the socket to the port 80, in order to get HTTP header. It is working! only I am having a hard time editing the program so it prints out the result straight away without having the user to type a character in order to display a line, I have tried to change the last bit of the code in "while" loop but nothing worked. please help!
-
Re: Java Socket Issue!
The readLine() method waits for a new line character. If you use this method, you have no choice but to wait for the line terminator. You can try a different method instead - like read() which reads a single character as an int. If the data coming from the client is simple ascii, then casting the int to a char should give you the character you want to see.