CREAMOS UN COMUNICADOR UDP EN JAVA2

 

 

 

Fichero exe

 

El código es el siguiente:

 

 

//package comunicador_udp;

 

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

 

public class Comunicador_UDP extends Frame implements ActionListener

{

      TextArea ta;

      TextField tf1,tf2,tf3,tf4,tf5;

      Button b1,b2;

      Label l1,l2,l3,l4;

 

      String ip_local,ip_remota,datos;

      int p_local,p_remoto;

      //declaramos lo que vamos a necesitar

      //Una clase del tipo hilo que todavia no hemos creado

      HiloEspera hilo,hilo1,hilo2;

      //declaramos las conexiones y los paquetes

      DatagramSocket conEnviar, conRecibir;

      DatagramPacket paqEnviar, paqRecibir;

     

      public Comunicador_UDP()

      {

      }

      public void inicializar()

      {

                  this.setTitle("Comunicador UDP");

                  ta=new TextArea();

                  ta.setBounds(10,40,280,150);

                  this.add(ta);

                  tf1=new TextField();

                  tf1.setBounds(10,200,180,20);

                  this.add(tf1);

                  b1=new Button("ENVIAR");

                  b1.setBounds(200,200,90,20);

                  this.add(b1);

                  b1.addActionListener(this);

 

                  l1=new Label("IP Local");

                  l1.setBounds(30,240,90,20);

                  this.add(l1);

                  tf2=new TextField();

                  tf2.setBounds(10,270,100,20);

                  this.add(tf2);

                  l2=new Label("Puerto Local");

                  l2.setBounds(120,240,90,20);

                  this.add(l2);

                  tf3=new TextField();

                  tf3.setBounds(130,270,50,20);

                  this.add(tf3);

 

                  l1=new Label("IP Remota");

                  l1.setBounds(30,300,90,20);

                  this.add(l1);

                  tf4=new TextField();

                  tf4.setBounds(10,330,100,20);

                  this.add(tf4);

                  l2=new Label("Puerto Remoto");

                  l2.setBounds(120,300,90,20);

                  this.add(l2);

                  tf5=new TextField();

                  tf5.setBounds(130,330,50,20);

                  this.add(tf5);

                  b2= new Button("Conectar");

                  b2.setBounds(210,275,80,80);

                  this.add(b2);

                  b2.addActionListener(this);

                  this.addWindowListener(new Cerrar);

 

            try

            {

                  tf2.setText(InetAddress.getLocalHost().getHostAddress());

                  tf4.setText(InetAddress.getLocalHost().getHostAddress());

                  tf3.setText("8888");

                  tf5.setText("8889");

            }

            catch(IOException ioe)

            {

            }

      }

      public void actionPerformed(ActionEvent ae)

      {

            if(ae.getSource()==b2)iniciarConexion();

            if(ae.getSource()==b1)enviarPaquetes();

      }

 

 

      public static void main(String[] args)

      {

                  Comunicador_UDP c = new Comunicador_UDP();

                  c.setLayout(null);

                  c.setSize(300,400);

                  c.setVisible(true);

                  c.inicializar();

      }

 

      //funcion para iniciar el programa con distintos usuarios

 

      public void iniciarConexion()

      {

            ip_local=tf2.getText();

            ip_remota=tf4.getText();

            p_local=Integer.valueOf(tf3.getText()).intValue();

            p_remoto=Integer.valueOf(tf5.getText()).intValue();

 

            //inicializamos las conexiones para enviar y para recibir

            try

            {

                  //dejo que la conexión para enviar la haga por cualquier puerto

                  conEnviar= new DatagramSocket();

                  //la conexión para recibir si la inicializo para el puerto de entrada

                  conRecibir= new DatagramSocket(p_local);

                  this.setTitle("Conectado al puerto " + p_local);

                  if (hilo==null)

                  {

                        hilo= new HiloEspera();

                        hilo.start();

                        ta.setText("Conectado con ip "+ ip_local +"\npuerto escucha "+ p_local+"\n"+tf1.getText());

     

                  }

                  else

                  {

                        hilo1= new HiloEspera();

                        hilo1.start();

                  }

            }

            catch(SocketException se)

            {

                  this.setTitle("No Conectado");

            }

      }

 

 

      //Clase Hilo que ejecuta la funcion esperar paquetes

      public class HiloEspera extends Thread

      {

            public HiloEspera()

            {}

            public void run()

            {

                  esperarPaquetes();

            }

      }

 

               

 

      //funcion esperar paquetes

 

      public void esperarPaquetes()

      {String datos="";

            while(true)

            {

                  byte array[]= new byte[50];

                  try

                  {

                        paqRecibir = new DatagramPacket(array,array.length);

                        conRecibir.receive(paqRecibir);

                        datos=new String(array);

                        ta.setText(ta.getText()+"\n"+datos);

                  }

 

                  catch(IOException ex)

                  {}

            }

      }

 

      public void enviarPaquetes()

      {

           

            ip_remota=tf4.getText();

            p_remoto=Integer.valueOf(tf5.getText()).intValue();

 

                  try

                  {

                        paqEnviar= new DatagramPacket(tf1.getText().getBytes(),tf1.getText().get_Length(),InetAddress.getAllByName(ip_remota)[0],p_remoto);

                        conEnviar.send(paqEnviar);

                        ta.setText(ta.getText()+"\n"+"Enviado "+ ip_remota +" al puerto "+ p_remoto+"\n"+tf1.getText());

                  }

 

                  catch(IOException ex)

                  {}

      }

 

 

      public void dispose()

      {

            hilo.stop();

            hilo1.stop();

      }

 

      class Cerrar extends WindowAdapter

      {

            public void windowClosing(WindowEvent e)

            {

                  e.getWindow().dispose();

                  System.exit(0);

            }

      }

}