Advertisement
Guest User

Untitled

a guest
Apr 20th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.net.DatagramPacket;
  3. import java.net.DatagramSocket;
  4. import java.net.InetAddress;
  5. import java.util.Scanner;
  6.  
  7. public class enviarMensaje extends Thread
  8. {
  9. private DatagramSocket socket;
  10. private InetAddress direccionObjetivo;
  11. private String nombre;
  12.  
  13. public enviarMensaje(DatagramSocket socket, InetAddress direccionObjetivo, String nombre)
  14. {
  15. this.socket = socket;
  16. this.direccionObjetivo = direccionObjetivo;
  17. this.nombre = nombre;
  18. }
  19.  
  20. @Override
  21. public void run()
  22. {
  23. String mensajeEnviado;
  24. Scanner keyboard = new Scanner(System.in);
  25. do
  26. {
  27. System.out.print("Mensaje a enviar: ");
  28. mensajeEnviado = nombre + ": " + keyboard.nextLine();
  29.  
  30. // Convierto el mensaje a bytes:
  31. byte[] bufferSalida = mensajeEnviado.getBytes();
  32.  
  33. // Creo mi paquete a enviar:
  34. DatagramPacket datagramaSalida; // Datagrama a enviar.
  35. InetAddress ipDestino = direccionObjetivo;
  36. int puerto = 7000; // Debe ser superior a 1023
  37. datagramaSalida = new DatagramPacket(bufferSalida, bufferSalida.length, ipDestino, puerto);
  38.  
  39. // Y lo envío:
  40. try
  41. {
  42. socket.send(datagramaSalida);
  43. }
  44. catch (IOException e)
  45. {
  46. e.printStackTrace();
  47. }
  48. System.out.println(mensajeEnviado);
  49. } while (!mensajeEnviado.equals("@SALIR"));
  50.  
  51.  
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement