赞
踩
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading;
-
- namespace UDP_DEMO_Send {
- static class Program {
- static void Main(string[] args) {
-
- InitUdp();
-
- Console.ReadKey();
- }
-
- #region UDP通信
-
- private static byte[] udpResult = new byte[1024];
- private static IPEndPoint udpTargetSend = null;
- private static UdpClient udpSend = null;
-
- private static int InitUdp() {
-
- var ip = "192.168.0.92";
- var port = 5021;
-
- Log(LogType.Open, "UDP Servise IP." + ip);
- Log(LogType.Open, "UDP Servise Port." + port);
-
- try {
- udpTargetSend = new IPEndPoint(IPAddress.Parse(ip), port);
-
- udpSend = new UdpClient(5011);
-
- while (true) {
-
- 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);
- if (r != 0) {
- Log(LogType.Recv, "rs err " + r);
- Thread.Sleep(1000);
- continue;
- }
- Log(LogType.Recv, BitConverter.ToString(udpResult, 0, udpResult.Length));
- Thread.Sleep(1000);
- }
-
- } catch (Exception e) {
- Log(LogType.Error, e.Message);
- }
-
- return 0;
-
- }
-
- static long send_expire = 0;
- static int send(byte[] buf, int ti = 3000) {
-
- udpResult = new byte[1024];
- Log(LogType.Send, BitConverter.ToString(buf));
-
- var r = 0;
-
- try {
- r = udpSend.Send(buf, buf.Length, udpTargetSend);
- } catch (Exception ex) {
- Log(LogType.Error, ex.Message);
- }
-
- send_expire = DateTime.Now.Ticks + ti * 10000;
- int len = 7;//最短数据长度位置
-
- for (; DateTime.Now.Ticks < send_expire; Thread.Sleep(20)) {
- IPEndPoint udpTargetRecv = null;
- try {
- if (udpSend.Available <= 0) continue;
- udpResult = udpSend.Receive(ref udpTargetRecv);
-
- if (udpResult.Length >= len) break;
-
- } catch (Exception e) {
- Log(LogType.Error, e.Message);
- return 4;
- }
- }
-
- if (udpResult == null || udpResult.Length <= 0) {
- Log(LogType.Recv, "time out");
- return 4;
- }
-
- return 0;
- }
-
- #endregion
-
- private enum LogType {
- Open,
- Send,
- Recv,
- Error,
- Info,
- }
-
- 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;
- var max = s.Length / 2;
- var buf = new byte[max];
- for (var i = 0; i < max; i++) buf[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);
- return buf;
- }
-
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。