网络传输之序列化

由于最近学习到序列化和反序列化的知识,便将以前写的网络传输代码加以修改,以下是传输一个数组的序列化

服务器端:

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

namespace 网络传输序列化服务器端
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener Listener = new TcpListener(IPAddress.Any, 8888);
            Listener.Start();

            while (true)
            {
                TcpClient client = Listener.AcceptTcpClient();
                NetworkStream netstream = client.GetStream();


                int[] S = new int[54];
                for (int i = 0; i < 54; i++)
                {
                    S[i] = i;

                }
             
                BinaryFormatter Formatter = new BinaryFormatter();
                //MemoryStream stream1 = new MemoryStream();

               //byte[] bytes=stream1.toArray();

               // Formatter.Serialize(netstream1, S);

                Formatter.Serialize(netstream, S);

                byte[] bytes = new byte[540];
                netstream.Write(bytes, bytes.Length, 0);
            
                netstream.Flush();
                netstream.Close();

           
            }
        }
    }
}

客户端:

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

namespace 网络传输序列化客户端
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient("127.0.0.1", 8888);
            NetworkStream stream = client.GetStream();
           
            BinaryFormatter Formatter = new BinaryFormatter();
            int[] R = (int[])Formatter.Deserialize(stream);

            for (int i = 0; i < 54; i++)
            {
                Console.WriteLine(R[i]);
            }
            stream.Close();

        }
    }
}
其中比较容易出现问题的就是在反序列化的时候出现“在分析完成之前就遇到流结尾”的问题,原先在服务器端使用了MemoryStream流会出现该问题,后来将服务器端和客户端全改成networkstream流避免了该问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值