UdpTool.cs
1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace OS.Spin.Common.Machine
{
public class UdpTool
{
public delegate void RecivedMeter(double meter);
public RecivedMeter RecivedMeterEvent;
private Socket _client;
public UdpTool(string ip,int port,string desIp,int desPort)
{
_client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_client.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
Thread t = new Thread(sendMsg);
t.Start();
Thread t2 = new Thread(ReciveMsg);
t2.Start();
}
/// <summary>
/// 向特定ip的主机的端口发送数据报
/// </summary>
private void sendMsg()
{
EndPoint point = new IPEndPoint(IPAddress.Parse("169.254.202.67"), 6001);
while (true)
{
string msg = Console.ReadLine();
_client.SendTo(Encoding.UTF8.GetBytes(msg), point);
}
}
/// <summary>
/// 接收发送给本机ip对应端口号的数据报
/// </summary>
private void ReciveMsg()
{
while (true)
{
EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
byte[] buffer = new byte[1024];
int length = _client.ReceiveFrom(buffer, ref point);//接收数据报
RecivedMeterEvent?.Invoke(0);
//string message = Encoding.UTF8.GetString(buffer, 0, length);
//Console.WriteLine(point.ToString() + message);
}
}
}
}