由于最近学习到序列化和反序列化的知识,便将以前写的网络传输代码加以修改,以下是传输一个数组的序列化
服务器端:
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流避免了该问题。