jueves, 25 de febrero de 2016

UDPSocket

/*UDPSocket_Cliente
//Agregar
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace ClienteUDP_Socket
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        byte[] bufferTx = new byte[1024];
        byte[] bufferRx = new byte[1024];
        string datosRx = "";
        string mensaje = "";

        Socket socketCliente = new Socket(AddressFamily.InterNetwork,
            SocketType.Dgram,
            ProtocolType.Udp);


        private void btnCOnectar_Click(object sender, EventArgs e)
        {
            if (txtDireccion.Text == "" || txtPuerto.Text == "")
            {
                MessageBox.Show("Ingrese los campos solicitados");
            }
            else
            {
                IPAddress direccionIp = IPAddress.Parse(txtDireccion.Text);
                int puertoRemoto = Convert.ToInt32(txtPuerto.Text);

                IPEndPoint puntoFinal = new IPEndPoint(direccionIp, puertoRemoto);

                //Envio de mensajes
                mensaje = "$Conectado";
                bufferTx = Encoding.ASCII.GetBytes(mensaje);

                socketCliente.SendTo(bufferTx, bufferTx.Length, SocketFlags.None, puntoFinal);

                //Recibir mensajes del servidor
                IPEndPoint recibe = new IPEndPoint(IPAddress.Any, 0);
                EndPoint puntoRemoto = (EndPoint)recibe;

                int cuenta = socketCliente.ReceiveFrom(bufferRx, ref  puntoRemoto);
                datosRx = Encoding.ASCII.GetString(bufferRx, 0, cuenta);
                string[] cadena = datosRx.Split('$');

                if (cadena[1] == "Hola")
                {
                    lblRecibir.Text = "Cliente conectado.";
                }
            }

        }

        private void btnEnviar_Click(object sender, EventArgs e)
        {
            if( txtDireccion.Text=="" || txtPuerto.Text =="" || txtEnviar.Text=="")
            {
                MessageBox.Show("Ingrese los campos solicitados");
            }
            else
            {
                IPEndPoint puntoFinal = new IPEndPoint(IPAddress.Parse(txtDireccion.Text), Convert.ToInt32(txtPuerto.Text));

                //Envio de mensajes
                //mensaje = "$Random";
                mensaje = txtEnviar.Text;
                bufferTx = Encoding.ASCII.GetBytes(mensaje);

                socketCliente.SendTo(bufferTx, bufferTx.Length, SocketFlags.None, puntoFinal);

                //Recibir mensajes del servidor
                IPEndPoint recibe = new IPEndPoint(IPAddress.Any, 0);
                EndPoint puntoRemoto = (EndPoint)recibe;

                int cuenta = socketCliente.ReceiveFrom(bufferRx, ref  puntoRemoto);
                datosRx = Encoding.ASCII.GetString(bufferRx, 0, cuenta);
                string[] cadena = datosRx.Split('$');

                lblMensajeRecibido.Text = "Mensaje Recibido: " + cadena[1];
            }
        }

    }
}

*/
======================================================================
/*UDPSocket_Servidor
//Agregar
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ServidorUDP_Socket
{
    class Program
    {
        static void Main(string[] args)
        {
            bool terminado = false;
            byte[] bufferRx = new byte[1024];
            byte[] bufferTx = new byte[1024];
            string datosRx = "";
            string datosTx = "";
            int puerto = 12345;
            int cuenta;

            IPAddress direccionIP = IPAddress.Parse("127.0.0.1");
            IPEndPoint puntoFinal = new IPEndPoint(direccionIP, puerto);
            Socket socketServidor = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram,
                ProtocolType.Udp);

            socketServidor.Bind(puntoFinal);

            //recibir mensaje del cliente
            IPEndPoint envio = new IPEndPoint(IPAddress.Any, 0);
            EndPoint puntoRemoto = (EndPoint)(envio);

            Console.WriteLine("Servidor iniciado....");

            while (!terminado)
            {
                cuenta = socketServidor.ReceiveFrom(bufferRx, ref puntoRemoto);
                datosRx = Encoding.ASCII.GetString(bufferRx, 0, cuenta);
                string[] cadena = datosRx.Split('$');

                if(cadena[1] == "Conectado")
                {
                    Console.WriteLine("Estado: " + datosRx);
                    Console.WriteLine("Esperando por mensajes...");
                   
                    //mensaje de envio del servidor al cliente
                    datosTx = "$Hola";
                    bufferTx = Encoding.ASCII.GetBytes(datosTx);

                }

                else if (cadena[1] == "Random")
                {
                    Console.WriteLine("Mensaje recibido: " + cadena[1]);                  
                    Random random = new Random();

                    int numAleatorio = random.Next(0, 101);
                    Console.WriteLine("Mensaje enviado por el servidor: " + numAleatorio);
                    Console.WriteLine("Esperando por mensajes...");

                    //mensaje de envio del servidor al cliente
                    datosTx = "$"+Convert.ToString(numAleatorio);
                    bufferTx = Encoding.ASCII.GetBytes(datosTx);

                }

                //Envio de mensaje
                socketServidor.SendTo(bufferTx, bufferTx.Length, SocketFlags.None, puntoRemoto);
            }
        }
    }
}

*/

No hay comentarios:

Publicar un comentario