
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text.RegularExpressions;
namespace UDP_DEMO_Send {
static void Main(string[] args) {
private static byte[] udpResult = new byte[1024];
private static IPEndPoint udpTargetSend = null;
private static UdpClient udpSend = null;
private static int InitUdp() {
Log(LogType.Open, "UDP Servise IP." + ip);
Log(LogType.Open, "UDP Servise Port." + port);
udpTargetSend = new IPEndPoint(IPAddress.Parse(ip), port);
udpSend = new UdpClient(5011);
var r = send(("5a3c 12 01 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-01-DB").ToBytes(), 500);
Log(LogType.Recv, "rs err " + r);
Log(LogType.Recv, BitConverter.ToString(udpResult, 0, udpResult.Length));
Log(LogType.Error, e.Message);
static long send_expire = 0;
static int send(byte[] buf, int ti = 3000) {
udpResult = new byte[1024];
Log(LogType.Send, BitConverter.ToString(buf));
r = udpSend.Send(buf, buf.Length, udpTargetSend);
Log(LogType.Error, ex.Message);
send_expire = DateTime.Now.Ticks + ti * 10000;
for (; DateTime.Now.Ticks < send_expire; Thread.Sleep(20)) {
IPEndPoint udpTargetRecv = null;
if (udpSend.Available <= 0) continue;
udpResult = udpSend.Receive(ref udpTargetRecv);
if (udpResult.Length >= len) break;
Log(LogType.Error, e.Message);
if (udpResult == null || udpResult.Length <= 0) {
Log(LogType.Recv, "time out");
private static void Log(LogType t, string msg) {
Console.Write($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:fff} [{t}] { msg}{Environment.NewLine}");
public static class Expand {
public static string Replace(this string s, string p, string r) {
return Regex.Replace(s, p, r);
public static byte[] ToBytes(this string s) {
s = Replace(s, @"[^\dA-Fa-f]+", "");
if (s.Length % 2 > 0) s = "0" + s;
for (var i = 0; i < max; i++) buf[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);