【问题标题】:How do you send a serialized object over net?如何通过网络发送序列化对象?
【发布时间】:2011-01-27 09:23:50
【问题描述】:

我正在尝试建立聊天!现在我的目标是接收来自用户的输入(将被提供给类中的函数),保存并通过网络将对象发送给用户。

到目前为止,这是我的代码:

namespace ConsoleApplication1
{
    class Program
    {       
        static void Main(string[] args)
        {
            TcpListener server = new TcpListener(IPAddress.Any, 5000);
            server.Start();
            Console.WriteLine("Server started");
            int a = 0;

            while (true)
            {
                TcpClient connection = server.AcceptTcpClient();
                Console.WriteLine("connection accepted");

                ThreadPool.QueueUserWorkItem(ProssecClient, connection);
            }
        }

        public static void ProssecClient(object o)
        {
            TcpClient connection = o as TcpClient;
            if (connection == null)
                return;
            StreamReader sr = new StreamReader(connection.GetStream());
            StreamWriter sw = new StreamWriter(connection.GetStream());
            string word = "";
            savedObject saved = new savedObject();

            try
            {
                while (true)
                {
                    sw.WriteLine(sr.ReadLine());
                    sw.Flush();

                    // here the server should read and retrieve, 
                    // everything that it gets to every user that logs in.
                }
            }
            catch
            { 
                Console.WriteLine("client left");
            }
        }           
    }
}

我将所有内容都保存在 binaryFormatter 中,如何将其发送给用户接收?

客户端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient connection = new TcpClient("127.0.0.1", 5000);
            StreamReader sr = new StreamReader(connection.GetStream());
            StreamWriter sw = new StreamWriter(connection.GetStream());
            savedObject saved = new savedObject();
            Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
            BinaryFormatter bformatter = new BinaryFormatter();
            string word = "";
            string allwords = "";

            Thread Listen = new Thread(deserialise);
            Listen.Start();

            while (true)
            {
                word = Console.ReadLine();
                allwords = saved.AllWords(word);
                sw.WriteLine(allwords);
                sw.Flush();
                Console.WriteLine(sr.ReadLine());

                //Serialize
                //bformatter.Serialize(stream, saved);
                //stream.Close();

                //sw.WriteLine(saved);
            }
        }
    }

    public static void deserialise()
    {
        //Deserialize
        //if (File.Exists("EmployeeInfo.osl"))
        //{
        //    stream = File.Open("EmployeeInfo.osl", FileMode.Open);
        //    bformatter = new BinaryFormatter();

        //    saved = (savedObject)bformatter.Deserialize(stream);
        //    stream.Close();
        //}

    }
}

[Serializable()]
class savedObject : ISerializable
{
    public string allwords;

    public string AllWords(string words)
    {
        allwords += words + " ";
        return allwords;
    }

    public void Words(SerializationInfo info, StreamingContext ctxt)
    {
        info.AddValue("RetrievedWord", allwords);
    }


    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        allwords = (String)info.GetValue("RetrievedWord", typeof(string));
    }
}

【问题讨论】:

    标签: c# serialization object chat binaryformatter


    【解决方案1】:

    考虑 WCF。

    它从一致的高级角度处理所有通信问题,包括安全性、不同协议等。

    它几乎是 .Net 中的通信标准,包含并取代了较旧的更底层技术。

    有关如何使用 WCF 构建聊天服务的优秀教程,请参阅 WCF / WPF Chat Application

    【讨论】:

      【解决方案2】:

      在 ProcessClient 方法中:

      TcpClient client = (TcpClient) connection;
      
      using(StreamWriter streamWriter = new StreamWriter(tcpClient.GetStream()))
      {
          BinaryFormatter binaryFormatter = new BinaryFormatter();
          binaryFormatter.Serialize(streamWriter, savedObject);
      }
      

      【讨论】:

      • 我已经稍微改变了我的代码。我依靠客户端保存序列化对象并将其传递给服务器,然后服务器将其传递回客户端。
      • 方法如下:客户端类型。这转到一个对象,该对象被序列化-----------> 转到服务器(服务器将序列化的对象传递给每个登录的用户)-----> 客户端反序列化对象并读取上面的内容......这是客户端代码......
      【解决方案3】:

      您可以使用 SOAP 架构(使用 XML 序列化而不是二元序列化)它会更容易实现。或者,如果您需要点对点聊天code here

      【讨论】:

      • 我认为如果您只使用 .net 对象,建议使用 BinaryFormatter - 如果您需要多平台支持 - 使用 SOAP 或 XML 序列化
      猜你喜欢
      • 2011-03-16
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      相关资源
      最近更新 更多