ReceiveFromAsync() public method

public ReceiveFromAsync ( SocketAsyncEventArgs e ) : bool
e SocketAsyncEventArgs
return bool
Example #1
0
        /// <summary>
        /// Create a UdpCommunication object using an existing Socket.
        /// </summary>
        public UdpCommunication(Socket socket, IPEndPoint endPoint)
        {
            _socket = socket;
            _endPoint = endPoint;

            // Start asynchronous read
            try
            {
                _receiveArgs = new SocketAsyncEventArgs();
                _receiveArgs.UserToken = _socket;
                _receiveArgs.RemoteEndPoint = _endPoint;
                _readBuffer = new byte[READBUFFERSIZE];
                _receiveArgs.SetBuffer(_readBuffer, 0, _readBuffer.Length);
                _receiveArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_socket_ReceivedData);
                if (_socket.ReceiveFromAsync(_receiveArgs) == false)  // Returns true if the I/O operation is pending. Returns false if the I/O operation completed synchronously and the SocketAsyncEventArgs.Completed event will not be raised.
                    _socket_ReceivedData(_socket, _receiveArgs);
            }
            catch (Exception ex)
            {
                // On failure free up the SocketAsyncEventArgs
                if (_receiveArgs != null)
                {
                    _receiveArgs.Completed -= new EventHandler<SocketAsyncEventArgs>(_socket_ReceivedData);
                    _receiveArgs.Dispose();
                    _receiveArgs = null;
                }

                throw;
            }
        }
Example #2
0
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            try
            {
                m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                m_ListenSocket.Bind(this.EndPoint);

                //Mono doesn't support it
                if (Platform.SupportSocketIOControlByCodeEnum)
                {
                    uint IOC_IN = 0x80000000;
                    uint IOC_VENDOR = 0x18000000;
                    uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                    byte[] optionInValue = { Convert.ToByte(false) };
                    byte[] optionOutValue = new byte[4];
                    m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);
                }

                var eventArgs = m_SaePool.Get();

                m_ListenSocket.ReceiveFromAsync(eventArgs);

                return true;
            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Example #3
0
        private void OnUdpReceive(object state)
        {
            try
            {
                SocketAsyncEventArgs seae = Pop();
                seae.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

                if (!mSocket.ReceiveFromAsync(seae))
                {
                    OnSeaeReceive(this, seae);
                }
            }
            catch (System.Net.Sockets.SocketException se)
            {
                OnChannelError(this, new ErrorEventArgs {
                    Error = se, Tag = "Server Udp Receive"
                });
                Dispose();
            }
            catch (Exception e)
            {
                OnChannelError(this, new ErrorEventArgs {
                    Error = e, Tag = "Server Udp Receive"
                });
            }
        }
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            try
            {
                m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                m_ListenSocket.Bind(this.EndPoint);

                uint IOC_IN = 0x80000000;
                uint IOC_VENDOR = 0x18000000;
                uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                byte[] optionInValue = { Convert.ToByte(false) };
                byte[] optionOutValue = new byte[4];
                m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);

                var eventArgs = new SocketAsyncEventArgs();

                eventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);
                eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

                int receiveBufferSize = config.ReceiveBufferSize <= 0 ? 2048 : config.ReceiveBufferSize;
                var buffer = new byte[receiveBufferSize];
                eventArgs.SetBuffer(buffer, 0, buffer.Length);

                m_ListenSocket.ReceiveFromAsync(eventArgs);

                return true;
            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
        // TODO: Correct ???
        public static IAsyncResult BeginReceiveFrom(this System.Net.Sockets.Socket socket
                                                    , byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags,
                                                    ref System.Net.EndPoint remoteEP
                                                    , AsyncCallback callback, object state)
        {
            ArraySegment <byte> buffer2 = buffer.ToArraySegment(offset, size);

            return(socket.ReceiveFromAsync(buffer2, socketFlags, remoteEP).AsApm(callback, state));
        }
Example #6
0
        protected void DoReceive()
        {
            lock (SyncRoot)
            {
                if (m_bReceive == false)
                {
                    this.LogError(MessageImportance.Highest, "error", string.Format("Can't call DoReceive, socket has been disposed by thread {0} or closed by {1}", this.ThreadNameDispose, this.ThreadNameShutdown));
                    return;
                }

                try
                {
                    LogMessage(MessageImportance.Lowest, this.OurGuid, string.Format("Called DoReceive"));

                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.RemoteEndPoint = m_ipEp; // new IPEndPoint(IPAddress.Any, this.m_ipEp.Port);
                    byte [] bBuffer = new byte[2048];
                    args.SetBuffer(bBuffer, 0, bBuffer.Length);
                    args.Completed += new EventHandler <SocketAsyncEventArgs>(OnReceiveUDP);
                    s.ReceiveFromAsync(args);
                }
                catch (SocketException e3) /// winso
                {
                    string strError = string.Format("{0} - {1}", e3.ErrorCode, e3.ToString());
                    LogError(MessageImportance.High, "SocketEXCEPTION", strError);
                    --(this.NumberOfReceivingThreads);
                    if (this.NumberOfReceivingThreads == 0 && this.OnReceivingStopped != null)
                    {
                        this.OnReceivingStopped(strError);
                    }
                    return;
                }
                catch (ObjectDisposedException e4) // socket was closed
                {
                    string strError = e4.ToString();
                    LogError(MessageImportance.High, "ObjectDisposedEXCEPTION", strError);
                    --(this.NumberOfReceivingThreads);
                    if (this.NumberOfReceivingThreads == 0 && this.OnReceivingStopped != null)
                    {
                        this.OnReceivingStopped(strError);
                    }
                    return;
                }
                catch (Exception e5)
                {
                    string strError = string.Format("{0}", e5.ToString());
                    LogError(MessageImportance.High, "EXCEPTION", strError);
                    --(this.NumberOfReceivingThreads);
                    if (this.NumberOfReceivingThreads == 0 && this.OnReceivingStopped != null)
                    {
                        this.OnReceivingStopped(strError);
                    }
                    return;
                }
            }
            return;
        }
Example #7
0
        public Task <UdpReceiveResult> ReceiveAsync()
        {
            ThrowIfDisposed();

            return(WaitAndWrap(_clientSocket.ReceiveFromAsync(
                                   new ArraySegment <byte>(_buffer, 0, MaxUDPSize),
                                   SocketFlags.None,
                                   _family == AddressFamily.InterNetwork ? IPEndPointStatics.Any : IPEndPointStatics.IPv6Any)));

            async Task <UdpReceiveResult> WaitAndWrap(Task <SocketReceiveFromResult> task)
            {
                SocketReceiveFromResult result = await task.ConfigureAwait(false);

                byte[] buffer = result.ReceivedBytes < MaxUDPSize?
                                _buffer.AsSpan(0, result.ReceivedBytes).ToArray() :
                                    _buffer;

                return(new UdpReceiveResult(buffer, (IPEndPoint)result.RemoteEndPoint));
            }
        }
Example #8
0
        public System.Threading.Tasks.Task <ReceivedUdpData> ReceiveAsync()
        {
            ThrowIfDisposed();

            var tcs = new TaskCompletionSource <ReceivedUdpData>();

            System.Net.EndPoint receivedFromEndPoint = new IPEndPoint(GetDefaultIpAddress(_Socket), 0);
            var state = new AsyncReceiveState(_Socket, receivedFromEndPoint);

            state.TaskCompletionSource = tcs;
#if NETSTANDARD1_3
            _Socket.ReceiveFromAsync(new System.ArraySegment <Byte>(state.Buffer), System.Net.Sockets.SocketFlags.None, state.EndPoint)
            .ContinueWith((task, asyncState) =>
            {
                if (this.IsDisposed)
                {
                    return;
                }

                try
                {
                    if (task.Status != TaskStatus.Faulted)
                    {
                        var receiveState      = asyncState as AsyncReceiveState;
                        receiveState.EndPoint = task.Result.RemoteEndPoint;
                        ProcessResponse(receiveState, () => task.Result.ReceivedBytes);
                    }
                }
                catch (ObjectDisposedException) { if (!this.IsDisposed)
                                                  {
                                                      throw;
                                                  }
                }                                                                                        //Only rethrow disposed exceptions if we're NOT disposed, because then they are unexpected.
            }, state);
#else
            try
            {
                _Socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, System.Net.Sockets.SocketFlags.None, ref state.EndPoint,
                                         new AsyncCallback((result) => ProcessResponse(state, () => state.Socket.EndReceiveFrom(result, ref state.EndPoint))), state);
            }
            catch (ObjectDisposedException) { if (!this.IsDisposed)
                                              {
                                                  throw;
                                              }
            }                                                                            //Only rethrow disposed exceptions if we're NOT disposed, because then they are unexpected.
#endif

            return(tcs.Task);
        }
Example #9
0
        /// <summary>
        /// Receives the specified number of bytes of data into the specified location of the data buffer,
        /// and stores the endpoint.
        /// </summary>
        /// <returns>The number of bytes received.</returns>
        /// <param name="buffer">An array of type Byte that is the storage location for received data.</param>
        /// <param name="offset">The position in the buffer parameter to store the received data.</param>
        /// <param name="size">The number of bytes to receive.</param>
        /// <param name="remoteEP">An EndPoint, passed by reference, that represents the remote server.</param>
        public Task <int> RecvFromAsync(byte [] buffer, int offset, int size, ref EndPoint remoteEP)
        {
            TaskCompletionSource <int> tcs = new TaskCompletionSource <int> ();
            var saea = new SocketAsyncEventArgs();

            saea.SetBuffer(buffer, offset, size);
            saea.RemoteEndPoint = remoteEP;
            saea.Completed     += (object sender, SocketAsyncEventArgs args) => { tcs.SetResult(args.BytesTransferred); };

            if (!m_socket.ReceiveFromAsync(saea))
            {
                tcs.SetResult(saea.BytesTransferred);
            }
            return(tcs.Task);
        }
Example #10
0
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            SaeState saeState = null;

            try
            {
                m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                m_ListenSocket.Bind(this.EndPoint);

                //Mono doesn't support it
                if (Platform.SupportSocketIOControlByCodeEnum)
                {
                    uint IOC_IN = 0x80000000;
                    uint IOC_VENDOR = 0x18000000;
                    uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                    byte[] optionInValue = { Convert.ToByte(false) };
                    byte[] optionOutValue = new byte[4];
                    m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);
                }

                saeState = m_SaePool.Get();
                var sae = saeState.Sae;
                sae.UserToken = saeState;
                sae.RemoteEndPoint = m_AnyEndPoint;
                sae.Completed += new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);

                if (!m_ListenSocket.ReceiveFromAsync(sae))
                    eventArgs_Completed(this, sae);

                return true;
            }
            catch (Exception e)
            {
                if (saeState != null)
                {
                    saeState.Sae.Completed -= new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);
                    m_SaePool.Return(saeState);
                }
                
                OnError(e);
                return false;
            }
        }
Example #11
0
        private void StartUdpAccept(MySAE mysae)
        {
            if (mysae == null)
            {
                byte[] udpBuffer = new byte[this._receiveBufferSize * 2];
                mysae            = new MySAE(true, true);
                mysae.Completed += new EventHandler <SocketAsyncEventArgs>(OnUdpAcceptCompleted);
                mysae.SetBuffer(udpBuffer, 0, udpBuffer.Length);
                mysae.BufferOffset   = 0;
                mysae.BufferLength   = udpBuffer.Length;
                mysae.RemoteEndPoint = _localEndAny;
                mysae.SocketId       = Guid.NewGuid();
                mysae.MsgId          = mysae.SocketId;
            }

            if (isRun)
            {
                if (!_listenSocketUdp.ReceiveFromAsync(mysae))
                {
                    OnUdpAcceptCompleted(this, mysae);
                }
            }
        }
Example #12
0
        private async Task<PingReply> SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            EndPoint endPoint = new IPEndPoint(address, 0);

            bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork;
            ProtocolType protocolType = isIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6;
            // Use the current thread's ID as the identifier.
            ushort identifier = (ushort)Environment.CurrentManagedThreadId;
            IcmpHeader header = new IcmpHeader()
            {
                Type = isIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest,
                Code = 0,
                HeaderChecksum = 0,
                Identifier = identifier,
                SequenceNumber = 0,
            };

            byte[] sendBuffer = CreateSendMessageBuffer(header, buffer);

            using (Socket socket = new Socket(address.AddressFamily, SocketType.Raw, protocolType))
            {
                socket.ReceiveTimeout = timeout;
                socket.SendTimeout = timeout;
                // Setting Socket.DontFragment and .Ttl is not supported on Unix, so ignore the PingOptions parameter.

                int ipHeaderLength = isIpv4 ? IpHeaderLengthInBytes : 0;
                await socket.SendToAsync(new ArraySegment<byte>(sendBuffer), SocketFlags.None, endPoint).ConfigureAwait(false);
                byte[] receiveBuffer = new byte[ipHeaderLength + IcmpHeaderLengthInBytes + buffer.Length];

                long elapsed;
                Stopwatch sw = Stopwatch.StartNew();
                // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response
                // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout.
                // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads.
                while ((elapsed = sw.ElapsedMilliseconds) < timeout)
                {
                    Task<SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync(
                                                                    new ArraySegment<byte>(receiveBuffer),
                                                                    SocketFlags.None,
                                                                    endPoint);
                    var cts = new CancellationTokenSource();
                    Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false);
                    cts.Cancel();
                    if (finished != receiveTask)
                    {
                        sw.Stop();
                        return CreateTimedOutPingReply();
                    }

                    SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult();
                    int bytesReceived = receiveResult.ReceivedBytes;
                    if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes)
                    {
                        continue; // Not enough bytes to reconstruct IP header + ICMP header.
                    }

                    byte type, code;
                    unsafe
                    {
                        fixed (byte* bytesPtr = receiveBuffer)
                        {
                            int icmpHeaderOffset = ipHeaderLength;
                            IcmpHeader receivedHeader = *((IcmpHeader*)(bytesPtr + icmpHeaderOffset)); // Skip IP header.
                            type = receivedHeader.Type;
                            code = receivedHeader.Code;

                            if (identifier != receivedHeader.Identifier
                                || type == (byte)IcmpV4MessageType.EchoRequest
                                || type == (byte)IcmpV6MessageType.EchoRequest) // Echo Request, ignore
                            {
                                continue;
                            }
                        }
                    }

                    sw.Stop();
                    long roundTripTime = sw.ElapsedMilliseconds;
                    int dataOffset = ipHeaderLength + IcmpHeaderLengthInBytes;
                    // We want to return a buffer with the actual data we sent out, not including the header data.
                    byte[] dataBuffer = new byte[bytesReceived - dataOffset];
                    Array.Copy(receiveBuffer, dataOffset, dataBuffer, 0, dataBuffer.Length);

                    IPStatus status = isIpv4
                                        ? IcmpV4MessageConstants.MapV4TypeToIPStatus(type, code)
                                        : IcmpV6MessageConstants.MapV6TypeToIPStatus(type, code);

                    return new PingReply(address, options, status, roundTripTime, dataBuffer);
                }

                // We have exceeded our timeout duration, and no reply has been received.
                sw.Stop();
                return CreateTimedOutPingReply();
            }
        }
        internal static byte[] UdpRecieve(Socket s, ref IPEndPoint EP)
        {
            string response = "Operation Timeout";

            byte[] msg = null;
            if (s != null)
            {
                // Create SocketAsyncEventArgs context object
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.RemoteEndPoint = EP;

                // Setup the buffer to receive the data
                socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);

                // Inline event handler for the Completed event.
                // Note: This even handler was implemented inline in order to make this method self-contained.
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object ss, SocketAsyncEventArgs e)
                {
                    if (e.SocketError == SocketError.Success)
                    {
                        // Retrieve the data from the buffer
                        msg = new byte[e.BytesTransferred];
                        Array.Copy(e.Buffer, e.Offset, msg, 0, e.BytesTransferred);
                    }
                    else
                    {
                        response = e.SocketError.ToString();
                    }

                    try
                    {
                        _clientDone[s].Set();
                    }
                    catch (KeyNotFoundException)
                    {
                    }
                });

                // Sets the state of the event to nonsignaled, causing threads to block
                _clientDone[s].Reset();

                // Make an asynchronous Receive request over the socket
                if (s.ReceiveFromAsync(socketEventArg) == false)
                {
                    if (socketEventArg.SocketError == SocketError.Success)
                    {
                        // Retrieve the data from the buffer
                        msg = new byte[socketEventArg.BytesTransferred];
                        Array.Copy(socketEventArg.Buffer, socketEventArg.Offset, msg, 0, socketEventArg.BytesTransferred);
                    }
                    else
                    {
                        response = socketEventArg.SocketError.ToString();
                    }
                    try
                    {
                        _clientDone[s].Set();
                    }
                    catch (KeyNotFoundException)
                    {
                    }
                }

                // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
                // If no response comes back within this time then proceed
                _clientDone[s].WaitOne();//(TimeOut);
            }

            return msg;
        }
Example #14
0
 public static Task <SocketReceiveFromResult> ReceiveFromAsync(this Socket socket, ArraySegment <byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint) =>
 socket.ReceiveFromAsync(buffer, socketFlags, remoteEndPoint);
		private void StartReceive (Socket socket, SocketAsyncEventArgs args, BufferValueReader reader)
		{
			if (!this.running)
				return;

			Interlocked.Increment (ref this.pendingAsync);

			try
			{
				args.SetBuffer (0, args.Buffer.Length);
				while (!socket.ReceiveFromAsync (args))
					Receive (this, args);
			}
			catch (ObjectDisposedException) // Socket is disposed, we're done.
			{
				Interlocked.Decrement (ref this.pendingAsync);
			}
		}
Example #16
0
        private SocketAsyncEventArgs CreateAsyncEventArgs(Socket socket, byte[] receiveBuffer)
        {
            var args = new SocketAsyncEventArgs();
            args.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);

            args.RemoteEndPoint = new IPEndPoint((socket.AddressFamily == AddressFamily.InterNetworkV6) ? IPAddress.IPv6None : IPAddress.None, 0);

            args.Completed += m_asyncEventArgs_Completed;

            if (!socket.ReceiveFromAsync(args))
            {
                m_asyncEventArgs_Completed(socket, args);
            }

            return args;
        }
Example #17
0
        public void ConnectToSimConnect()
        {
            try
            {
                sc = new SimConnect("VE_SC_WPF", (IntPtr)0, 0, scReady, 0);

                sc.OnRecvClientData += sc_OnRecvClientData;
                sc.OnRecvCustomAction += sc_OnRecvCustomAction;
                sc.OnRecvEvent += sc_OnRecvEvent;
                sc.OnRecvEventFilename += sc_OnRecvEventFilename;
                sc.OnRecvEventFrame += sc_OnRecvEventFrame;
                sc.OnRecvEventObjectAddremove += sc_OnRecvEventObjectAddremove;
                sc.OnRecvException += sc_OnRecvException;
                sc.OnRecvGroundInfo += sc_OnRecvGroundInfo;
                sc.OnRecvNull += sc_OnRecvNull;
                sc.OnRecvObserverData += sc_OnRecvObserverData;
                sc.OnRecvOpen += sc_OnRecvOpen;
                sc.OnRecvQuit += sc_OnRecvQuit;
                sc.OnRecvSimobjectData += sc_OnRecvSimobjectData;
                sc.OnRecvSimobjectDataBytype += sc_OnRecvSimobjectDataBytype;
                sc.OnRecvSynchronousBlock += sc_OnRecvSynchronousBlock;
                sc.OnRecvSystemState += sc_OnRecvSystemState;

                _udpRecv = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                _udpRecv.Bind(new IPEndPoint(IPAddress.Any, 49000));

                SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                e.Completed += OnReceive;
                e.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                e.SetBuffer(new byte[255], 0, 255);

                if (!_udpRecv.ReceiveFromAsync(e))
                    OnReceive(_udpRecv, e);
            }
            catch (COMException)
            {
                Console.WriteLine("Unable to connect to SimConnect");
            }
            catch (Exception)
            {
            }
            finally
            {

            }

            bgThread = new Thread(new ThreadStart(scMessageThread));
            bgThread.IsBackground = true;
            bgThread.Start();
        }
Example #18
0
 private void StartReceive(Socket socket)
 {
     SocketAsyncEventArgs parameters = new SocketAsyncEventArgs();
     if (socket.AddressFamily == AddressFamily.InterNetwork)
         parameters.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
     else
         parameters.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
     parameters.Completed += new EventHandler<SocketAsyncEventArgs>(ReceiveCallback);
     parameters.SetBuffer(new byte[4096], 0, 4096);
     socket.ReceiveFromAsync(parameters);
 }
Example #19
0
        private void SetupUDPRecv()
        {
            // setup receiver
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 49005);

            SimulatorRECV = new Socket(AddressFamily.InterNetwork,
                            SocketType.Dgram, ProtocolType.Udp);

            SimulatorRECV.Bind(ipep);

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            recvargs.RemoteEndPoint = sender;
            recvargs.SetBuffer(udpdata, 0, udpdata.Length);

            SimulatorRECV.ReceiveFromAsync(recvargs);
        }
Example #20
0
 bool Utils.Wrappers.Interfaces.ISocket.ReceiveFromAsync(SocketAsyncEventArgs e)
 {
     return(InternalSocket.ReceiveFromAsync(e));
 }
Example #21
0
        protected override void open()
        {
            if (_socket == null || _socket.Connected == false)
            {
                System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + "  %%%%%%%%%%%%%%%%%% UdpCommunication.Open.  Attempting to connect to " + _udpHostName + ":" + _udpPort + ".");

                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // interNetwork is IPv4

                // Get the end point to send data to.
                IPAddress ipAddress;
                if (System.Net.IPAddress.TryParse(_udpHostName, out ipAddress) == false)
                    ipAddress = Dns.GetHostEntry(_udpHostName).AddressList[0];
                _endPoint = new IPEndPoint(ipAddress, _udpPort);

                IPEndPoint bindingEndPoint = null;
                if (IPAddress.Broadcast.Equals(_endPoint.Address))
                {
                    string localHostName = System.Net.Dns.GetHostName();
                    IPAddress[] ipAddresses = Dns.GetHostEntry(localHostName).AddressList;
                    foreach (IPAddress ip in ipAddresses)
                    {
                        if (ip.AddressFamily == AddressFamily.InterNetwork)
                        {
                            bindingEndPoint = new IPEndPoint(ip, _udpPort); // This needs to be a local ip address, and the port to listen on.
                            break;
                        }
                    }
                    if (bindingEndPoint == null)
                        throw new Exception("There is no outside ip address for this machine.");
                    _socket.EnableBroadcast = true;
                }
                else
                {
                    //IPEndPoint bindingEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), _udpPort);
                    bindingEndPoint = new IPEndPoint(IPAddress.Any, _udpPort); // This needs to be a local ip address, and the port to listen on.
                }
                _socket.Bind(bindingEndPoint);

                // Start listening
                _receiveArgs = new SocketAsyncEventArgs();
                try
                {
                    _receiveArgs.UserToken = _socket;
                    _receiveArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0); // it doesn't appear to matter what address or port you set this to it just needs to be set to something.
                    _readBuffer = new byte[READBUFFERSIZE];
                    _receiveArgs.SetBuffer(_readBuffer, 0, _readBuffer.Length);
                    _receiveArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_socket_ReceivedData);
                    if (_socket.ReceiveFromAsync(_receiveArgs) == false)  // Returns true if the I/O operation is pending. Returns false if the I/O operation completed synchronously and the SocketAsyncEventArgs.Completed event will not be raised.
                        _socket_ReceivedData(_socket, _receiveArgs);
                }
                catch
                {
                    // On failure free up the SocketAsyncEventArgs
                    if (_receiveArgs != null)
                    {
                        _receiveArgs.Completed -= new EventHandler<SocketAsyncEventArgs>(_socket_ReceivedData);
                        _receiveArgs.Dispose();
                        _receiveArgs = null;
                    }

                    throw;
                }
            }
        }