/// <summary> /// Start a connection of Tcp Client Socket /// </summary> void StartWork(object obj) { //set Terminate flag TerminateFlag.Reset(); Active = true; // Connect to a remote device. try { IPEndPoint remoteEP = new IPEndPoint(IpAddress, Port); // Create Udp Client Udp = new UdpClient(remoteEP); // Create the state object. UdpStateObject state = new UdpStateObject(); state.client = Udp; state.ep = remoteEP; // Connect to the remote endpoint Udp.BeginReceive(ReadCallback, state); //wait until stop is called TerminateFlag.WaitOne(); // Release the socket. Udp.Close(); Active = false; } catch (Exception e) { Active = false; Console.WriteLine(e.ToString()); } }
/// <summary> /// Read a Callback send from client /// </summary> /// <param name="ar"></param> void ReadCallback(IAsyncResult ar) { try { UdpStateObject state = (UdpStateObject)(ar.AsyncState); // Read data from the remote device. UdpClient client = state.client; IPEndPoint ep = state.ep; byte[] buffer = client.EndReceive(ar, ref ep); if (buffer.Length > 0) { // There might be more data, so store the data received so far. state.message.AddRange(buffer); //trigger new message event if (PackageReceived != null) { PackageReceived(state.message.ToArray()); } } //establish new message and read more UdpStateObject newState = new UdpStateObject(); newState.client = client; newState.ep = ep; client.BeginReceive(new AsyncCallback(ReadCallback), newState); } catch (Exception) { //re-initialize receive callback UdpStateObject state = (UdpStateObject)(ar.AsyncState); // Read data from the remote device. UdpClient client = state.client; IPEndPoint ep = state.ep; //establish new message and read more UdpStateObject newState = new UdpStateObject(); newState.client = client; newState.ep = ep; while (true) { try { client.BeginReceive(new AsyncCallback(ReadCallback), newState); break; } catch (Exception) { } } } }