Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

NOMBRE DEL PROYECTO: SOCKETS

CLASE CONEXIÓN
package sockets.conexion;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Conexion


{
private final int PUERTO = 1234;
private final String HOST = "localhost";
protected String mensajeServidor;
protected ServerSocket ss;
protected Socket cs;
protected DataOutputStream salidaServidor, salidaCliente;

public Conexion(String tipo) throws IOException


{
if(tipo.equalsIgnoreCase("servidor"))
{
ss = new ServerSocket(PUERTO);
cs = new Socket();
}
else
{
cs = new Socket(HOST, PUERTO);
}
}
}
CLASE SERVIDOR

package sockets.servidor;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import sockets.conexion.Conexion;

public class Servidor extends Conexion


{
public Servidor() throws IOException{super("servidor");}

public void startServer()


{
try
{
System.out.println("Esperando...");

cs = ss.accept();

System.out.println("Cliente en línea");

salidaCliente = new DataOutputStream(cs.getOutputStream());

salidaCliente.writeUTF("Petición recibida y aceptada");

BufferedReader entrada = new BufferedReader(new


InputStreamReader(cs.getInputStream()));

while((mensajeServidor = entrada.readLine()) != null)


{

System.out.println(mensajeServidor);
}

System.out.println("Fin de la conexión");

ss.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}

CLASE CLIENTE
package sockets.cliente;

import java.io.DataOutputStream;
import java.io.IOException;
import sockets.conexion.Conexion;

public class Cliente extends Conexion


{
public Cliente() throws IOException{super("cliente");}

public void startClient()


{
try
{

salidaServidor = new DataOutputStream(cs.getOutputStream());

for (int i = 0; i < 2; i++)


{

salidaServidor.writeUTF("Este es el mensaje número " + (i+1) + "\n");


}

cs.close();

}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
CLASE MAIN SERVIDOR

package sockets.main;

import java.io.IOException;
import sockets.servidor.Servidor;

public class MainServidor


{
public static void main(String[] args) throws IOException
{
Servidor serv = new Servidor();

System.out.println("Iniciando servidor\n");
serv.startServer();
}
}

CLASE CLIENTE

package sockets.main;

import java.io.IOException;
import sockets.cliente.Cliente;

public class MainCliente


{
public static void main(String[] args) throws IOException
{
Cliente cli = new Cliente();

System.out.println("Iniciando cliente\n");
cli.startClient();
}
}

You might also like