Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using System.Windows.Forms;
- namespace WindowsFormsApplication1
- {
- public partial class Form1 : Form
- {
- IPEndPoint myEP;
- string targetIP;
- static public string Timestamp(bool ms, bool trailspace)
- {
- string t;
- if (ms)
- t = DateTime.UtcNow.ToString(format: "yyyyMMdd.HHmmss.fff");
- else
- t = DateTime.UtcNow.ToString(format: "yyyyMMdd.HHmmss");
- if(trailspace)t=t+" ";
- return (t);
- }
- static public int BufferToStrings(Byte[] buf, Int32 buflen, string[] sout, Int16 maxlen)
- {
- int count = 0;
- int idx = 0;
- try
- {
- var sb = new StringBuilder();
- for (int index = 0; index < buflen; index++)
- {
- sb.Append(buf[index].ToString(format: "X2")+" ");
- if (++idx > maxlen)
- {
- sout[count++] = sb.ToString();
- sb.Clear();
- idx = 0;
- }
- }
- if (idx > 0) sout[count++] = sb.ToString();
- return count;
- }
- catch (Exception e)
- {
- return 0;
- }
- }
- // State object for reading client data asynchronously
- public class StateObject
- {
- // Client socket.
- public Socket WorkSocket = null;
- // Size of receive buffer.
- public const int BufferSize = 1024;
- // Receive buffer.
- public byte[] Buffer = new byte[BufferSize];
- // Received data string.
- public StringBuilder Sb = new StringBuilder();
- }
- public class AsynchronousSocketListener
- {
- // Thread signal.
- public static ManualResetEvent AllDone = new ManualResetEvent(initialState: false);
- public AsynchronousSocketListener()
- {
- }
- public static void StartListening(int port)
- {
- // Data buffer for incoming data.
- var bytes = new Byte[1024];
- // Establish the local endpoint for the socket.
- // The DNS name of the computer
- // running the listener is "host.contoso.com".
- //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
- IPAddress ipAddress = IPAddress.Parse(ipString: "127.0.0.0");
- var localEndPoint = new IPEndPoint(ipAddress, port);
- // Create a TCP/IP socket.
- var listener = new Socket(AddressFamily.InterNetwork,
- SocketType.Stream, ProtocolType.Tcp);
- // Bind the socket to the local endpoint and listen for incoming connections.
- try
- {
- listener.Bind(localEndPoint);
- listener.Listen(backlog: 100);
- while (true)
- {
- // Set the event to nonsignaled state.
- AllDone.Reset();
- // Start an asynchronous socket to listen for connections.
- //Console.WriteLine("Waiting for a connection...");
- listener.BeginAccept(
- new AsyncCallback(AcceptCallback),
- listener);
- // Wait until a connection is made before continuing.
- AllDone.WaitOne();
- }
- }
- catch (Exception e)
- {
- int err = 1;
- //Console.WriteLine(e.ToString());
- }
- //Console.WriteLine("nPress ENTER to continue...");
- //Console.Read();
- }
- public static void AcceptCallback(IAsyncResult ar)
- {
- // Signal the main thread to continue.
- AllDone.Set();
- // Get the socket that handles the client request.
- var listener = (Socket)ar.AsyncState;
- Socket handler = listener.EndAccept(ar);
- // Create the state object.
- var state = new StateObject();
- state.WorkSocket = handler;
- handler.BeginReceive(state.Buffer, offset: 0, size: StateObject.BufferSize, socketFlags: 0, callback: new AsyncCallback(ReadCallback), state: state);
- }
- public static void ReadCallback(IAsyncResult ar)
- {
- String content = String.Empty;
- // Retrieve the state object and the handler socket
- // from the asynchronous state object.
- var state = (StateObject)ar.AsyncState;
- Socket handler = state.WorkSocket;
- // Read data from the client socket.
- int bytesRead = handler.EndReceive(ar);
- if (bytesRead > 0)
- {
- // There might be more data, so store the data received so far.
- state.Sb.Append(Encoding.ASCII.GetString(
- state.Buffer, index: 0, count: bytesRead));
- // Check for end-of-file tag. If it is not there, read
- // more data.
- content = state.Sb.ToString();
- if (content.IndexOf(value: "<EOF>")> -1)
- {
- // All the data has been read from the
- // client. Display it on the console.
- //Console.WriteLine("Read {0} bytes from socket. n Data : {1}",
- // content.Length, content );
- // Echo the data back to the client.
- Send(handler, content);
- }
- else
- {
- // Not all data received. Get more.
- handler.BeginReceive(state.Buffer, offset: 0, size: StateObject.BufferSize, socketFlags: 0, callback: new AsyncCallback(ReadCallback), state: state);
- }
- }
- }
- private static void Send(Socket handler, String data)
- {
- // Convert the string data to byte data using ASCII encoding.
- byte[] byteData = Encoding.ASCII.GetBytes(data);
- // Begin sending the data to the remote device.
- handler.BeginSend(byteData, offset: 0, size: byteData.Length, socketFlags: 0, callback: new AsyncCallback(SendCallback), state: handler);
- }
- private static void SendCallback(IAsyncResult ar)
- {
- try
- {
- // Retrieve the socket from the state object.
- var handler = (Socket)ar.AsyncState;
- // Complete sending the data to the remote device.
- int bytesSent = handler.EndSend(ar);
- //Console.WriteLine("Sent {0} bytes to client.", bytesSent);
- handler.Shutdown(SocketShutdown.Both);
- handler.Close();
- }
- catch (Exception e)
- {
- int err = 1;
- //Console.WriteLine(e.ToString());
- }
- }
- }
- private UdpClient listener;
- private bool keepRunning = true;
- private Thread uthread = null;
- public Form1()
- {
- InitializeComponent();
- }
- void MLog(string s)
- {
- if (LB.InvokeRequired)
- {
- LB.Invoke(new MethodInvoker(() => { MLog(s); }));
- }
- else
- {
- LB.Items.Add(s);
- LB.TopIndex = LB.Items.Count - (LB.Height / LB.ItemHeight);
- }
- }
- private void ThreadRun()
- {
- Byte[] data;
- Byte[] resp = Encoding.ASCII.GetBytes(s: "x01x02x03");
- string[] s;
- var ep = new IPEndPoint(IPAddress.Parse(ipString: "192.168.1.1"), port: 5361);
- s = new string[6];
- while (true == keepRunning)
- {
- try
- {
- data = listener.Receive(ref ep);
- targetIP = ep.Address.ToString();
- int t = BufferToStrings(data, data.Length, s, maxlen: 16);
- for (int i = 0; i < t;i++)
- {
- if (s[i].Length > 0)
- MLog(Timestamp(ms: true, trailspace: true)+"["+targetIP + "] " + s[i]);
- }
- // do something with rx data
- //listener.Send(resp, 3);
- }
- catch { }
- }
- }
- private void Button1Click(object sender, EventArgs e)
- {
- int port;
- if (Int32.TryParse(tPort.Text, out port))
- {
- // StartListening(port);
- //TcpListener tcps;
- MLog("open UDP " + port+"...");
- listener = new UdpClient();
- listener.ExclusiveAddressUse = false;
- myEP = new IPEndPoint(IPAddress.Any, port: 5361);
- listener.Client.Bind(myEP);
- listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue: true);
- listener.EnableBroadcast = true;
- //IPAddress groupAddr = IPAddress.Parse("224.2.3.4");
- //listener.JoinMulticastGroup(groupAddr);
- uthread = new Thread(new ThreadStart(ThreadRun));
- uthread.Start();
- }
- }
- private void BSendClick(object sender, EventArgs e)
- {
- //byte[] b = Encoding.ASCII.GetBytes("abcdef");
- byte[] b ={0x0B,0xE2,0x8C,0x41,0xA7,0x0F};
- IPAddress ipa = IPAddress.Parse(targetIP);
- var tep = new IPEndPoint(ipa, port: 5361);
- var bep = new IPEndPoint(IPAddress.Parse(ipString: "192.168.99.255"), port: 5361);
- listener.Connect(tep);
- listener.Send(b, bytes: 6);
- listener.Connect(bep);
- listener.Send(b, bytes: 6);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement