using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Xxxxx
{
class UdpClient
{
private Socket client;
private string strIp;
private int port;
private byte[] msg;
public void UdpClientSocketCreat(string strIp,int port)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ip = IPAddress.Parse(strIp);
IPEndPoint endPoint = new IPEndPoint(ip, port);
client.Connect(endPoint);
Thread thread = new Thread(ReciveMsg);
thread.IsBackground = true;
thread.Start(client);
Console.WriteLine("客户端已成功开启!");
}
void SendMsg()
{
EndPoint point = new IPEndPoint(IPAddress.Parse(strIp), port);
client.SendTo(msg, point);
}
public void Send(string strIp, int port, byte[] msg)
{
this.strIp = strIp;
this.port = port;
this.msg = msg;
Thread t1 = new Thread(SendMsg);
t1.Start();
}
void ReciveMsg(object o)
{
Socket client = o as Socket;
while (true)
{
try
{
EndPoint point = new IPEndPoint(IPAddress.Any, 0);
byte[] buffer = new byte[2000];
int length = client.Receive(buffer);
}
catch (Exception)
{
client.Close();
}
}
}
}
}
UdpClient udpClient = new UdpClient();
byte[] buf = {0x01,0x02,0x03,0x04,0x05};
udpClient.Send("192.168.90.100",3456, buf);