Skip to content

Instantly share code, notes, and snippets.

@adrinavarro
Created November 25, 2012 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrinavarro/4144206 to your computer and use it in GitHub Desktop.
Save adrinavarro/4144206 to your computer and use it in GitHub Desktop.
práctica tcp 1/2
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");
}
}
}
}
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