Created
November 25, 2012 16:15
-
-
Save adrinavarro/4144206 to your computer and use it in GitHub Desktop.
práctica tcp 1/2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
class TCPCliente { | |
public static void main(String args[]) throws Exception { | |
String frase = null; | |
String respuesta; | |
String server; | |
Integer port; | |
try { | |
frase = args[0]; | |
} catch(ArrayIndexOutOfBoundsException e) { | |
System.out.println("Frase no introducida"); | |
} | |
try { | |
server = args[1]; | |
} catch(ArrayIndexOutOfBoundsException e) { | |
server = "127.0.0.1"; | |
} | |
try { | |
port = Integer.parseInt(args[2]); | |
} catch(ArrayIndexOutOfBoundsException e) { | |
port = 2510; | |
} catch(NumberFormatException e) { | |
port = 2510; | |
} | |
if(frase != null) { | |
try { | |
Socket socketCliente = new Socket(server, port); | |
BufferedReader entradaDesdeServidor = new BufferedReader(new InputStreamReader(socketCliente.getInputStream())); | |
DataOutputStream salidaServidor = new DataOutputStream(socketCliente.getOutputStream()); | |
salidaServidor.writeBytes(frase + '\n'); | |
respuesta = entradaDesdeServidor.readLine(); | |
System.out.println("Hemos recibido: " + respuesta); | |
socketCliente.close(); | |
} catch (ConnectException e) { | |
System.out.println("Servidor no encendido"); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
class TCPServidor { | |
public static void main(String args[]) throws Exception { | |
Integer port; | |
try { | |
port = Integer.parseInt(args[0]); | |
} catch(ArrayIndexOutOfBoundsException e) { | |
port = 2510; | |
} catch(NumberFormatException e) { | |
port = 2510; | |
} | |
ServerSocket socketAtendido = new ServerSocket(port); | |
while(true) { | |
Socket socketConexion = socketAtendido.accept(); | |
BufferedReader entradaDesdeCliente = new BufferedReader(new InputStreamReader(socketConexion.getInputStream())); | |
DataOutputStream salidaACliente = new DataOutputStream(socketConexion.getOutputStream()); | |
System.out.println(socketConexion.getInetAddress().getHostAddress() + ' ' + socketConexion.getPort()); | |
salidaACliente.writeBytes(entradaDesdeCliente.readLine() + '\n'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment