111,113
社区成员




首先你的Users对象必须是再Client端和Server端共享的DLL来的,而且要可序列化,根据你的问题我建了三个Project:
1.ClassLibrary1.dll,放User class,在Client端和Server都同时引用它。
[Serializable]
public class Users
{
public int Age { get; set; }
public string Name { get; set; }
public object Sex { get; set; }
public object Address { get; set; }
public ulong Phone { get; set; }
public object Content { get; set; }
}
2.client project
class Program
{
private static UdpClient udpClient;
static void Main(string[] args)
{
udpClient = new UdpClient();
SendData();
Console.Read();
}
public static void SendData()
{
try
{
//定义对方主机和端口
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9800);
//实例化并赋值
Users user = new Users
{
Name = "test",
Sex = "1",
Age = 27,
Address = "127.0.0.1",
Phone = 13698756236,
Content = "test"
};
List<Users> list = new List<Users>();
list.Add(user);
//序列化集合
Stream s = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter(); //二进制方式
bf.Serialize(s, list); //序列化保存配置文件对象list
byte[] by = new byte[s.Length];
s.Position = 0;
s.Read(by, 0, by.Length);
//发送
udpClient.Send(by, by.Length, ipPoint);
Console.WriteLine("success!~");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
3.Server:
class Program
{
private static UdpClient udpClient;
static void Main(string[] args)
{
udpClient = new UdpClient(9800); //这里Server端的监听端口必须是Client发送的端口
ReceiveData();
Console.Read();
}
private static void ReceiveData()
{
IPEndPoint point = new IPEndPoint(IPAddress.Any, 0);
//接收数据,储存在byte数组里
byte[] bytes = udpClient.Receive(ref point);
Stream s = new MemoryStream(bytes);
BinaryFormatter bf = new BinaryFormatter();
List<Users> list = bf.Deserialize(s) as List<Users>; //获取
Console.WriteLine(list[0].Name + " >> " + list[0].Address);
}
}