c#通过网络发送接收对象?

时间:2010-04-20 10:17:27

标签: c# client serialization

我正在研究服务器/客户端项目。客户端将询问服务器的信息,服务器会将它们发送回客户端

信息可以是字符串,数字,数组,列表,arraylist或任何其他对象。到目前为止我找到的解决方案是序列化对象(数据)并发送它然后反序列化它以进行处理。

这是服务器代码:

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);
        }
    }

这是应返回对象的客户端代码

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;

        }

我需要知道一个好的序列化/序列化以及如何将它集成到上面的解决方案中。

2 个答案:

答案 0 :(得分:11)

更新(8年后)

有多种方法可以通过网络发送数据。它通常涉及一端的某种形式的序列化和另一端的反序列化。 虽然,我的原始答案可行,但我认为gRPC将是一个更好的解决方案,因为它允许客户端和服务器用不同的语言编写。更重要的是,它提供了流媒体功能和许多社区插件(用于指标,跟踪,日志记录等) 只要有可能,尽量不要重新发明轮子......


原始答案

您考虑过使用Windows Communication Foundation服务吗? WCF为您提供可扩展的API,它支持最常用的协议。更多的WCF内置了序列化/反序列化。

如果您确实不想使用WCF,则可以使用Binary Serialization

这是二进制序列化的示例用法:

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 );
}

以下是关于binary serialization的整篇文章。

-Pavel

答案 1 :(得分:2)

您可以使用JavaScriptSerializer将对象序列化为json。它非常轻巧,易于使用。 只是不要忘记添加对System.Web.Extensions.dll的引用

e.g:

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

并在另一个班级

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