2010-04-20 15 views
5

Estoy trabajando en un proyecto de servidor/cliente. El cliente le pedirá información al servidor y el servidor los enviará de vuelta al clienteC# send receive object over network?

La información puede ser cadena, número, matriz, lista, lista de arrays o cualquier otro objeto. La solución que encontré hasta ahora es serializar el objeto (datos) y enviarlo, luego deserializarlo para procesarlo.

Aquí es el código del servidor:

public void RunServer(string SrvIP,int SrvPort) 
    { 
     try 
     { 
      var ipAd = IPAddress.Parse(SrvIP); 


      /* Initializes the Listener */ 
      if (ipAd != null) 
      { 
       var myList = new TcpListener(ipAd, SrvPort); 

       /* Start Listeneting at the specified port */ 
       myList.Start(); 

       Console.WriteLine("The server is running at port "+SrvPort+"..."); 
       Console.WriteLine("The local End point is :" + myList.LocalEndpoint); 
       Console.WriteLine("Waiting for a connection....."); 


       while (true) 
       { 
        Socket s = myList.AcceptSocket(); 
        Console.WriteLine("Connection accepted from " + s.RemoteEndPoint); 

        var b = new byte[100]; 
        int k = s.Receive(b); 
        Console.WriteLine("Recieved..."); 
        for (int i = 0; i < k; i++) 
         Console.Write(Convert.ToChar(b[i])); 
        string cmd = Encoding.ASCII.GetString(b); 
        if (cmd.Contains("CLOSE-CONNECTION")) 
         break; 
        var asen = new ASCIIEncoding(); 

        // sending text 
        s.Send(asen.GetBytes("The string was received by the server.")); 

        // the line bove to be modified to send serialized object? 


        Console.WriteLine("\nSent Acknowledgement"); 
        s.Close(); 
        Console.ReadLine(); 
       } 
       /* clean up */ 

       myList.Stop(); 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("Error..... " + e.StackTrace); 
     } 
    } 

aquí es el código de cliente que debe devolver un objeto

public object runClient(string SrvIP, int SrvPort) 
     { 
      object obj = null; 
      try 
      { 
       var tcpclnt = new TcpClient(); 
       Console.WriteLine("Connecting....."); 

       tcpclnt.Connect(SrvIP, SrvPort); 
       // use the ipaddress as in the server program 


       Console.WriteLine("Connected"); 
       Console.Write("Enter the string to be transmitted : "); 

       var str = Console.ReadLine(); 
       Stream stm = tcpclnt.GetStream(); 

       var asen = new ASCIIEncoding(); 
       if (str != null) 
       { 
        var ba = asen.GetBytes(str); 
        Console.WriteLine("Transmitting....."); 

        stm.Write(ba, 0, ba.Length); 
       } 

       var bb = new byte[2000]; 

       var k = stm.Read(bb, 0, bb.Length); 

       string data = null; 

       for (var i = 0; i < k; i++) 
        Console.Write(Convert.ToChar(bb[i])); 

       //convert to object code ?????? 

       Console.ReadLine(); 

       tcpclnt.Close(); 
      } 

      catch (Exception e) 
      { 
       Console.WriteLine("Error..... " + e.StackTrace); 
      } 

      return obj; 

     } 

necesito saber una buena serializar/serializar y cómo integrarla en el solución arriba.

Respuesta

10

Update (8 años más tarde)

Existen múltiples formas de enviar datos a través de la red. Por lo general, implica alguna forma de serialización en un extremo y deserialización en el otro. Aunque mi respuesta original funcionaría, creo que gRPC sería una mejor solución ya que permite que el cliente y el servidor se escriban en diferentes idiomas. Lo que es más, ofrece funciones de transmisión y una gran cantidad de plugins de la comunidad (para las métricas, seguimiento, registro, etc.) Siempre que sea posible, trate de no reinventar la rueda ...


respuesta original

¿ha considerado utilizar Windows Communication Foundation servicios? WCF le ofrece API extensible que admite los protocolos más comunes listos para usar. Y lo que es más, WCF ha incorporado la serialización/deserialización.

Si no desea utilizar WCF, puede usar Binary Serialization.

Este es un ejemplo de uso del serialización binaria:

private Stream SerializeMultipleObjects() 
{ 
    // Initialize a storage medium to hold the serialized object 
    Stream stream = new MemoryStream(); 

    // Serialize an object into the storage medium referenced by 'stream' object. 
    BinaryFormatter formatter = new BinaryFormatter(); 

    // Serialize multiple objects into the stream 
    formatter.Serialize(stream, obOrders); 
    formatter.Serialize(stream, obProducts); 
    formatter.Serialize(stream, obCustomers); 

    // Return a stream with multiple objects 
    return stream; 
} 

private void DeSerializeMultipleObject(Stream stream) 
{ 
    // Construct a binary formatter 
    BinaryFormatter formatter = new BinaryFormatter(); 

    // Deserialize the stream into object 
    Orders  obOrders = (Orders)formatter.Deserialize(stream); 
    Products obProducts = (Products)formatter.Deserialize(stream); 
    Customers obCustomers = (Customer)formatter.Deserialize(stream); 
} 

Aquí está el artículo completo sobre binary serialization.

-Pavel

+0

asignan así que soy nuevo en todo esto No me importa lo que camino por recorrer para alcanzar y aprender lo que necesito todo lo que necesito es un servicio/solución de cliente que ayudan a que envíe los valores/objetos al servidor y obtener resultados/respuestas del servidor como enviar un comando (cadena) "getProcesses" y el servidor enviará una matriz o un objeto (Process [] processlist = Process.GetProcesses();) de nuevo para el cliente ¿eso es difícil? ¿Cuál es la mejor manera de hacerlo? –

+0

pero cómo usar tu código con mi código? –

+1

Te recomiendo que leas uno de los tutoriales disponibles "Cómo comenzar con WCF", como: http://msdn.microsoft.com/en-us/library/ms734712(VS.100).aspx http://weblogs.asp.net/ralfw/archive/2007/04/14/a-truely-simple-example-to-get-started-with-wcf.aspx http://msdn.microsoft.com/en-us /library/ms730144.aspx –

2

Puede serializar sus objetos en json, usando JavaScriptSerializer .. Es muy liviano y fácil de usar. Pero no se olvide de añadir una referencia a System.Web.Extensions.dll

por ejemplo:

var js = new JavaScriptSerializer(); 
var data = js.Deserialize<MyClass>(receivedString); 

y en la otra clase

var js = new JavaScriptSerializer(); 
var serializedData = js.Serialize(dataObject); 
+0

¿Por qué usted recomienda JavaScript cuando la pregunta es sobre C#? – YetAnotherRandomUser

+0

@YetAnotherRandomUser JSON se utiliza comúnmente como un formato de serialización para todo lo que se transmita a través de HTTP, independientemente del idioma que utilice el cliente y/o servidor para interpretar los datos, no está menos relacionado con C# que XML.Gracias :-) –