1.首先创建可以被序列化的程序集,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Instance
{
[Serializable]
public class Instance
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
}
2.然后创建服务器端,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace UDP服务器端
{
class Program
{
static void Main(string[] args)
{
UdpClient receivingUdpClient = new UdpClient(11000);//创建UDPClient对象
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);//创建IPEndPoint对象
try
{
while (true)
{
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);//接收远程发送的UDP数据报
MemoryStream P_MemoryStream = new MemoryStream(receiveBytes);//创建内存流对象
P_MemoryStream.Seek(0, SeekOrigin.Begin);//调整内存流指针位置
Instance.Instance P_Instance = //从内存流中反序列化得到Instance对象
new BinaryFormatter().Deserialize(P_MemoryStream) as Instance.Instance;
Console.WriteLine(//输出客户端地址信息
string.Format("远程IP地址为:{0}", RemoteIpEndPoint.Address.ToString()));
Console.WriteLine(//输出客户端端口信息
string.Format("远程主机打开的端口为{0}", RemoteIpEndPoint.Port.ToString()));
Console.WriteLine(//输出客户端Instance对象信息
string.Format("内容,姓名:{0} 年龄:{1} 地址:{2}", P_Instance.Name,
P_Instance.Age, P_Instance.Address));
}
}
catch (Exception e)//捕获异常
{
Console.WriteLine(e.ToString());//输出异常信息
}
Console.ReadLine();//主线程挂起
}
}
}
3.最后创建客户端,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace UDP客户端
{
class Program
{
static void Main(string[] args)
{
UdpClient udpClient = new UdpClient();//创建UDPClient对象
IPAddress ipAddress = IPAddress.Parse("192.168.1.100");//创建IPAddress对象
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 11000);//创建IPEndPoint对象
MemoryStream P_MemoryStream = new MemoryStream();//创建内存流对象
new BinaryFormatter().Serialize(P_MemoryStream, new Instance.Instance()//将序列化信息放入内存流
{
Name="王军",
Age=29,
Address="长春"
});
try
{
while (true)
{
udpClient.Send(P_MemoryStream.ToArray(), P_MemoryStream.ToArray().Length, ipEndPoint);//发送字节数组到指定的网络端点
Console.ReadLine();//主线程挂起
}
}
catch (Exception e)//捕获异常
{
Console.WriteLine(e.ToString());//输出异常信息
}
Console.ReadLine();//主线程挂起
}
}
}