class ClienteFecha {
public static void main( String[] args ) {
String servidor = "localhost";
int puerto = 13; // puerto de daytime
try {
// Se abre un socket conectado al servidor y al
// puerto estándar de echo
Socket socket = new Socket( servidor,puerto );
System.out.println( "Socket Abierto." );
// Se consigue el canal de entrada
BufferedReader entrada = new BufferedReader(
new InputStreamReader( socket.getInputStream() ) );
System.out.println( "Hora actual en localhost:" );
System.out.println( "\t"+entrada.readLine() );
System.out.println( "Hora actual con la clase date:" );
System.out.println( "\t" + new Date() );
// Se cierra el canal de entrada
entrada.close();
// Se cierra el socket
socket.close();
} catch( UnknownHostException e ) {
System.out.println( e );
System.out.println("Debes estar conectado para que esto funcione bien." );
} catch( IOException e ) {
System.out.println( e );
}
}
}
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
System.out.println("estoy después de crear el socket");
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("estoy después de aceptar un cliente");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
Having the two classes above (or any example referring to sockets also serves my question),
- What code runs first?
- What happens if the server executes the code faster and reads the
in.readLine()
instruction before my client has sent the data?
The question in general would be, How does my server ensure that it first receives the data and then reads / reviews the entry?