Advertisement
Guest User

Untitled

a guest
Sep 2nd, 2015
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.34 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Windows.Forms;
  7.  
  8. namespace WindowsFormsApplication1
  9. {
  10. public partial class Form1 : Form
  11. {
  12. IPEndPoint myEP;
  13. string targetIP;
  14. static public string Timestamp(bool ms, bool trailspace)
  15. {
  16. string t;
  17. if (ms)
  18. t = DateTime.UtcNow.ToString(format: "yyyyMMdd.HHmmss.fff");
  19. else
  20. t = DateTime.UtcNow.ToString(format: "yyyyMMdd.HHmmss");
  21. if(trailspace)t=t+" ";
  22. return (t);
  23. }
  24. static public int BufferToStrings(Byte[] buf, Int32 buflen, string[] sout, Int16 maxlen)
  25. {
  26. int count = 0;
  27. int idx = 0;
  28. try
  29. {
  30. var sb = new StringBuilder();
  31. for (int index = 0; index < buflen; index++)
  32. {
  33. sb.Append(buf[index].ToString(format: "X2")+" ");
  34. if (++idx > maxlen)
  35. {
  36. sout[count++] = sb.ToString();
  37. sb.Clear();
  38. idx = 0;
  39. }
  40. }
  41. if (idx > 0) sout[count++] = sb.ToString();
  42. return count;
  43. }
  44. catch (Exception e)
  45. {
  46. return 0;
  47. }
  48.  
  49. }
  50. // State object for reading client data asynchronously
  51. public class StateObject
  52. {
  53. // Client socket.
  54. public Socket WorkSocket = null;
  55. // Size of receive buffer.
  56. public const int BufferSize = 1024;
  57. // Receive buffer.
  58. public byte[] Buffer = new byte[BufferSize];
  59. // Received data string.
  60. public StringBuilder Sb = new StringBuilder();
  61. }
  62.  
  63. public class AsynchronousSocketListener
  64. {
  65. // Thread signal.
  66. public static ManualResetEvent AllDone = new ManualResetEvent(initialState: false);
  67.  
  68. public AsynchronousSocketListener()
  69. {
  70. }
  71.  
  72. public static void StartListening(int port)
  73. {
  74. // Data buffer for incoming data.
  75. var bytes = new Byte[1024];
  76.  
  77. // Establish the local endpoint for the socket.
  78. // The DNS name of the computer
  79. // running the listener is "host.contoso.com".
  80. //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
  81. IPAddress ipAddress = IPAddress.Parse(ipString: "127.0.0.0");
  82. var localEndPoint = new IPEndPoint(ipAddress, port);
  83.  
  84. // Create a TCP/IP socket.
  85. var listener = new Socket(AddressFamily.InterNetwork,
  86. SocketType.Stream, ProtocolType.Tcp);
  87.  
  88. // Bind the socket to the local endpoint and listen for incoming connections.
  89. try
  90. {
  91. listener.Bind(localEndPoint);
  92. listener.Listen(backlog: 100);
  93.  
  94. while (true)
  95. {
  96. // Set the event to nonsignaled state.
  97. AllDone.Reset();
  98.  
  99. // Start an asynchronous socket to listen for connections.
  100. //Console.WriteLine("Waiting for a connection...");
  101. listener.BeginAccept(
  102. new AsyncCallback(AcceptCallback),
  103. listener);
  104.  
  105. // Wait until a connection is made before continuing.
  106. AllDone.WaitOne();
  107. }
  108.  
  109. }
  110. catch (Exception e)
  111. {
  112. int err = 1;
  113. //Console.WriteLine(e.ToString());
  114. }
  115.  
  116. //Console.WriteLine("nPress ENTER to continue...");
  117. //Console.Read();
  118. }
  119.  
  120. public static void AcceptCallback(IAsyncResult ar)
  121. {
  122. // Signal the main thread to continue.
  123. AllDone.Set();
  124.  
  125. // Get the socket that handles the client request.
  126. var listener = (Socket)ar.AsyncState;
  127. Socket handler = listener.EndAccept(ar);
  128.  
  129. // Create the state object.
  130. var state = new StateObject();
  131. state.WorkSocket = handler;
  132. handler.BeginReceive(state.Buffer, offset: 0, size: StateObject.BufferSize, socketFlags: 0, callback: new AsyncCallback(ReadCallback), state: state);
  133. }
  134.  
  135. public static void ReadCallback(IAsyncResult ar)
  136. {
  137. String content = String.Empty;
  138.  
  139. // Retrieve the state object and the handler socket
  140. // from the asynchronous state object.
  141. var state = (StateObject)ar.AsyncState;
  142. Socket handler = state.WorkSocket;
  143.  
  144. // Read data from the client socket.
  145. int bytesRead = handler.EndReceive(ar);
  146.  
  147. if (bytesRead > 0)
  148. {
  149. // There might be more data, so store the data received so far.
  150. state.Sb.Append(Encoding.ASCII.GetString(
  151. state.Buffer, index: 0, count: bytesRead));
  152.  
  153. // Check for end-of-file tag. If it is not there, read
  154. // more data.
  155. content = state.Sb.ToString();
  156. if (content.IndexOf(value: "<EOF>")> -1)
  157. {
  158. // All the data has been read from the
  159. // client. Display it on the console.
  160.  
  161.  
  162. //Console.WriteLine("Read {0} bytes from socket. n Data : {1}",
  163. // content.Length, content );
  164.  
  165.  
  166. // Echo the data back to the client.
  167. Send(handler, content);
  168. }
  169. else
  170. {
  171. // Not all data received. Get more.
  172. handler.BeginReceive(state.Buffer, offset: 0, size: StateObject.BufferSize, socketFlags: 0, callback: new AsyncCallback(ReadCallback), state: state);
  173. }
  174. }
  175. }
  176.  
  177. private static void Send(Socket handler, String data)
  178. {
  179. // Convert the string data to byte data using ASCII encoding.
  180. byte[] byteData = Encoding.ASCII.GetBytes(data);
  181.  
  182. // Begin sending the data to the remote device.
  183. handler.BeginSend(byteData, offset: 0, size: byteData.Length, socketFlags: 0, callback: new AsyncCallback(SendCallback), state: handler);
  184. }
  185.  
  186. private static void SendCallback(IAsyncResult ar)
  187. {
  188. try
  189. {
  190. // Retrieve the socket from the state object.
  191. var handler = (Socket)ar.AsyncState;
  192.  
  193. // Complete sending the data to the remote device.
  194. int bytesSent = handler.EndSend(ar);
  195. //Console.WriteLine("Sent {0} bytes to client.", bytesSent);
  196.  
  197. handler.Shutdown(SocketShutdown.Both);
  198. handler.Close();
  199.  
  200. }
  201. catch (Exception e)
  202. {
  203. int err = 1;
  204. //Console.WriteLine(e.ToString());
  205. }
  206. }
  207.  
  208. }
  209.  
  210. private UdpClient listener;
  211. private bool keepRunning = true;
  212. private Thread uthread = null;
  213.  
  214. public Form1()
  215. {
  216. InitializeComponent();
  217. }
  218. void MLog(string s)
  219. {
  220. if (LB.InvokeRequired)
  221. {
  222. LB.Invoke(new MethodInvoker(() => { MLog(s); }));
  223. }
  224. else
  225. {
  226. LB.Items.Add(s);
  227. LB.TopIndex = LB.Items.Count - (LB.Height / LB.ItemHeight);
  228. }
  229. }
  230. private void ThreadRun()
  231. {
  232. Byte[] data;
  233. Byte[] resp = Encoding.ASCII.GetBytes(s: "x01x02x03");
  234. string[] s;
  235. var ep = new IPEndPoint(IPAddress.Parse(ipString: "192.168.1.1"), port: 5361);
  236. s = new string[6];
  237. while (true == keepRunning)
  238. {
  239. try
  240. {
  241. data = listener.Receive(ref ep);
  242. targetIP = ep.Address.ToString();
  243. int t = BufferToStrings(data, data.Length, s, maxlen: 16);
  244. for (int i = 0; i < t;i++)
  245. {
  246. if (s[i].Length > 0)
  247. MLog(Timestamp(ms: true, trailspace: true)+"["+targetIP + "] " + s[i]);
  248. }
  249. // do something with rx data
  250. //listener.Send(resp, 3);
  251. }
  252. catch { }
  253. }
  254. }
  255. private void Button1Click(object sender, EventArgs e)
  256. {
  257. int port;
  258. if (Int32.TryParse(tPort.Text, out port))
  259. {
  260. // StartListening(port);
  261. //TcpListener tcps;
  262. MLog("open UDP " + port+"...");
  263. listener = new UdpClient();
  264. listener.ExclusiveAddressUse = false;
  265. myEP = new IPEndPoint(IPAddress.Any, port: 5361);
  266. listener.Client.Bind(myEP);
  267. listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue: true);
  268. listener.EnableBroadcast = true;
  269. //IPAddress groupAddr = IPAddress.Parse("224.2.3.4");
  270. //listener.JoinMulticastGroup(groupAddr);
  271. uthread = new Thread(new ThreadStart(ThreadRun));
  272. uthread.Start();
  273.  
  274. }
  275. }
  276.  
  277. private void BSendClick(object sender, EventArgs e)
  278. {
  279. //byte[] b = Encoding.ASCII.GetBytes("abcdef");
  280. byte[] b ={0x0B,0xE2,0x8C,0x41,0xA7,0x0F};
  281. IPAddress ipa = IPAddress.Parse(targetIP);
  282. var tep = new IPEndPoint(ipa, port: 5361);
  283. var bep = new IPEndPoint(IPAddress.Parse(ipString: "192.168.99.255"), port: 5361);
  284. listener.Connect(tep);
  285. listener.Send(b, bytes: 6);
  286. listener.Connect(bep);
  287. listener.Send(b, bytes: 6);
  288. }
  289. }
  290. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement