Comunicación TCP Cliente-Servidor usando Mono C#



Esto es una ejemplo básico de comunicación Cliente Servidor desarrollado en Mono C#, las pruebas se realizaron en Ubuntu 10.04, pero igual corre en windows solo debes habilitar los permisos en el puerto 8080 para las pruebas.

Tomar en cuenta que los ejecutables se hicieron para correr en consola,ustedes deberán realizar las adaptaciones para u programa con interfaz

Lo primero a realizar será crear es la librería que va a ser utilizada por ambos ejecutables.


using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
 
namespace TestCode.Remoting
{
  public class SampleObject : MarshalByRefObject
  {
    private int counter;
    public SampleObject()
    {
      counter = 0;
    }
    public int GetCount()
    {
      counter++;
      return counter;
    }
    // Make object live forever
    public override Object InitializeLifetimeService()
    {
      return null;
    }
  }
}

Ahora vamos a armar el que hará de Servidor.

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace TestCode.Remoting
{
  public class SampleServer
  {
    public static void Main(string [] args)
    {
      // Create an instance of a channel
      TcpChannel channel = new TcpChannel(8080);
      ChannelServices.RegisterChannel(channel,false);
      // Create an instance of our object
      SampleObject obj = new SampleObject();
      // Publish our object
      RemotingServices.Marshal(obj, "SampleObject");
      System.Console.WriteLine("Press the enter key to exit...");
      System.Console.ReadLine();
    }
  }
}

ahora el cliente que se llamará "cliente.cs"

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace TestCode.Remoting
{
  public class SampleClient
  {
    public static void Main(string [] args)
    {
      // Create a channel for communicating w/ the remote object
      // Notice no port is specified on the client
      TcpChannel chan = new TcpChannel();
      ChannelServices.RegisterChannel(chan,false);
 
      // Create an instance of the remote object
      SampleObject obj = (SampleObject) Activator.GetObject(
        typeof(TestCode.Remoting.SampleObject),
        "tcp://localhost:8080/SampleObject" );
      // Use the object
      if( obj.Equals(null) )
      {
        System.Console.WriteLine("Error: unable to locate server");
      }
      else
      {
        Console.WriteLine("counter: {0}", obj.GetCount());
      }
    }
  }
}

y por ultimo y lo mas importante es el compilar los tres ficheros, debemos empezar por la librería ya que los otros programas necesitan

gmcs /t:library /debug /r:System.Runtime.Remoting.dll remotolib.cs
gmcs /debug /r:remotolib.dll /r:System.Runtime.Remoting.dll server.cs
gmcs /debug /r:remotolib.dll /r:System.Runtime.Remoting.dll cliente.cs

si ejecutaste los tres lineas con comando y no te apareció ningún mensaje es que todo resulto bien.


Comentarios

Entradas populares de este blog

Arduino Nano - Relay y sensor de movimiento PIR

crear DLL y compilar con MONO y C#