a = new IPEndPoint(IPAddress.Parse(string), 56666);
新建一个终结点,这个终结点保存了IP地址和端口号,可以保存自己和对方的。
me = new UdpClient(a);
传入自己的IP创建的终结点,将自己计算机转换为UDP客户端
public void GetIP()
{
IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
string myIp = "";
for (int i = 0; i < ipe.AddressList.Length; ++i)
{
if (ipe.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
myIp = ipe.AddressList[i].ToString();
break;
}
}
a = new IPEndPoint(IPAddress.Parse(myIp), 56666);
me = new UdpClient(a);
}
获得自身IP并创建为客户端(局域网IP)
me.Send(sendto,sendto.Length,new IPEndPoint);
从自己的客户端发送消息,发送的消息是前两个参数为信息内容(byte数组),第三参数是发送到的终结点;
发送信息就一句话
public byte[] byy = new byte[] { };
public List<byte> byyy = new List<byte>();
byte[] byyyy = new byte[256];
IpEndPoint c;
Class retxin = new Class ();//解析出的类型
public void lisen()
{
while (true)
{
byy = me.Receive(ref c);
if (byy.Length > 0)
{
foreach (byte a in byy)
{
byyy.Add(a);
}
if (byyy.Count >= 256)
{
for (int i = 0; i < 256; i++)
{
byyyy[i] = byyy[i];
}
byyy.RemoveRange(0, 256);
retxin = (Class)BtoO(byyyy);
//接下来的逻辑是解析retxin中的数据
}
}
}
}
默认接受到的信息为256字节并进行粘包拆包,将接受的信息转换为class类型保存到retxin并解析
public byte[] OtoB(object obj)
{
byte[] buff;
MemoryStream ms = new MemoryStream();
IFormatter iFormatter = new BinaryFormatter();
iFormatter.Serialize(ms, obj);
buff = ms.GetBuffer();
return buff;
}
Objuct类型转化为二进制字节流
public object BtoO(byte[] buff)
{
object obj;
MemoryStream ms = new MemoryStream(buff);
IFormatter iFormatter = new BinaryFormatter();
obj = iFormatter.Deserialize(ms);
return obj;
}
二进制字节流传唤为Objuct类型