/// <summary>
        /// 在ReceiveStart调用之前设置pipline.
        /// </summary>
        /// <param name="pipline"></param>
        /// <returns></returns>
        public async Task <UdpRemote> ListenAsync(ReceiveCallback receiveHandle, IMessagePipeline pipline)
        {
            IsListening = true;
            System.Threading.ThreadPool.QueueUserWorkItem(state =>
            {
                AcceptAsync();
            });

            if (connected.TryDequeue(out var remote))
            {
                if (remote != null)
                {
                    remote.MessagePipeline = pipline;
                    remote.ReceiveStart();
                    return(remote);
                }
            }
            if (TaskCompletionSource == null)
            {
                TaskCompletionSource = new TaskCompletionSource <UdpRemote>();
            }

            var res = await TaskCompletionSource.Task;

            TaskCompletionSource   = null;
            res.MessagePipeline    = pipline;
            res.OnReceiveCallback += receiveHandle;
            res.ReceiveStart();
            return(res);
        }
Example #2
0
        public Form1()
        {
            InitializeComponent();



            delReceive           = delreceive;
            delReceiveCount      = delreceiveCount;
            delReceiveLightState = delreceiveLightState;

            pA = new PictureBox[31] {
                pictureBox1, pictureBox2, pictureBox3, pictureBox4, pictureBox5, pictureBox6, pictureBox7, pictureBox8, pictureBox9, pictureBox10, pictureBox11, pictureBox12, pictureBox13, pictureBox14, pictureBox15, pictureBox16, pictureBox17, pictureBox18, pictureBox19, pictureBox20, pictureBox21, pictureBox22, pictureBox23, pictureBox24, pictureBox25, pictureBox26, pictureBox27, pictureBox28, pictureBox29, pictureBox30, pictureBox31
            };
            pB = new PictureBox[42] {
                pictureBox32, pictureBox33, pictureBox34, pictureBox35, pictureBox36, pictureBox37, pictureBox38, pictureBox39, pictureBox40, pictureBox41, pictureBox42, pictureBox43, pictureBox44, pictureBox45, pictureBox46, pictureBox47, pictureBox48, pictureBox49, pictureBox50, pictureBox51, pictureBox52, pictureBox53, pictureBox54, pictureBox55, pictureBox56, pictureBox57, pictureBox58, pictureBox59, pictureBox60, pictureBox61, pictureBox62, pictureBox63, pictureBox64, pictureBox65, pictureBox66, pictureBox67, pictureBox68, pictureBox69, pictureBox70, pictureBox71, pictureBox72, pictureBox73
            };
            try
            {
                IPEndPoint point = new IPEndPoint(IPAddress.Parse("119.146.68.41"), 5000);
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socketClient.Connect(point);
                Send();
                n = 1;
                comboBox1.Items.Add("自动模式");
                comboBox1.Items.Add("手动模式");
                comboBox1.Text = "自动模式";
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start();
            }
            catch (Exception)
            { }
        }
Example #3
0
        //注册服务端
        public static ErrCode RegisterService(string strName, ReceiveCallback OnReceive, object objCallback)
        {
            // 使用GCHandleType.Pinned会报错,改用GCHandleType.Normal就不出错了
            // System.ArgumentException”类型的未经处理的异常在 mscorlib.dll 中发生
            // 其他信息: Object 包含非基元或非直接复制到本机结构中的数据。
            //GC.SuppressFinalize(OnReceive);这个方法告诉CLR不要再调用obj对象的终结器了. 试过但依然会被终结.

            //针对委托,可以使用Marshal.GetFunctionPointerForDelegate从delegate封送到非托管函数,或者使用Marshal.GetDelegateForFunctionPointer从非托管函数里面取出。
            //在封送到非托管函数时需要确保GC不要回收委托(需要保持引用但不需要Pinned)。

            //C#的对象不能在Native中进行处理,只能保存以待之后再传回给C#调用,保存的方式为C#用GCHandle引用对象,然后把GCHandle转成IntPtr,传给Native作为指针保存
            GCHandle gcHandle = GCHandle.Alloc(OnReceive, GCHandleType.Normal);

            gcHandleLis.Add(gcHandle);

            IntPtr funPtr = Marshal.GetFunctionPointerForDelegate(OnReceive); // 锁定委托函数的指针
            // ReceiveCallback funReceive = (ReceiveCallback) Marshal.GetDelegateForFunctionPointer(funPtr,typeof( ReceiveCallback));这是从函数指针中转换为委托

            IntPtr objIntPtr = IntPtr.Zero;

            if (objCallback != null)
            {
                gcHandle  = GCHandle.Alloc(objCallback, GCHandleType.Normal);
                objIntPtr = (IntPtr)gcHandle;
                //gcHandle = (GCHandle)objIntPtr;
            }
            return(UnsafeNativeMethods.Register(strName, funPtr, objIntPtr));
        }
Example #4
0
        private void ReceiveHandle()
        {
            //接收数据处理线程
            byte[] data = new byte[1024];

            while (true)
            {
                if (UdpInit.mySocket == null || UdpInit.mySocket.Available < 1)
                {
                    Thread.Sleep(10);
                    continue;
                }

                //接收UDP数据报,引用参数RemotePoint获得源地址
                try
                {
                    int             rlen = UdpInit.mySocket.ReceiveFrom(data, ref UdpInit.RemotePoint);
                    ReceiveCallback tx   = SetReceiveData;
                    tx(rlen, data);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                    //data = Mcu.ModbusUdp.MBReqConnect();
                    UdpSend.UdpSendData(Mcu.ModbusUdp.MBReqConnect(), Mcu.ModbusUdp.MBReqConnect().Length, UdpInit.BroadcastRemotePoint);
                    Debug.WriteLine("Search server");
                }
            }
        }
Example #5
0
        private void Receive()
        {
            Message message = null;

            while (!_requestStop)
            {
                message = _transceiver.Receive();
                if (message != null)
                {
                    switch (message.Code)
                    {
                    case (Int32)SystemMessageCode.TaskOverEvent:
                    {
                        Terminate();
                        TaskOverEventArgs args = message.GetContent <TaskOverEventArgs>();
                        OnTaskOver(args);
                    }
                    break;

                    case (Int32)SystemMessageCode.ActivatorErrorEvent:
                    {
                        Terminate();
                        ActivatorErrorEventArgs args = message.GetContent <ActivatorErrorEventArgs>();
                        OnActivatorError(args);
                    }
                    break;

                    default:
                        ReceiveCallback?.Invoke(message);
                        break;
                    }
                }
            }
        }
Example #6
0
        private async Task ReceiveAsync()
        {
            try
            {
                _logger.HttpReceiveStarted();

                while (await Input.WaitToReadAsync())
                {
                    if (_connectionState != ConnectionState.Connected)
                    {
                        _logger.SkipRaisingReceiveEvent();
                        // drain
                        Input.TryRead(out _);
                        continue;
                    }

                    if (Input.TryRead(out var buffer))
                    {
                        _logger.ScheduleReceiveEvent();
                        _ = _eventQueue.Enqueue(async () =>
                        {
                            _logger.RaiseReceiveEvent();

                            // Copying the callbacks to avoid concurrency issues
                            ReceiveCallback[] callbackCopies;
                            lock (_callbacks)
                            {
                                callbackCopies = new ReceiveCallback[_callbacks.Count];
                                _callbacks.CopyTo(callbackCopies);
                            }

                            foreach (var callbackObject in callbackCopies)
                            {
                                try
                                {
                                    await callbackObject.InvokeAsync(buffer);
                                }
                                catch (Exception ex)
                                {
                                    _logger.ExceptionThrownFromCallback(nameof(OnReceived), ex);
                                }
                            }
                        });
                    }
                    else
                    {
                        _logger.FailedReadingMessage();
                    }
                }

                await Input.Completion;
            }
            catch (Exception ex)
            {
                Output.TryComplete(ex);
                _logger.ErrorReceiving(ex);
            }

            _logger.EndReceive();
        }
Example #7
0
 public unsafe static extern int ReceiveMessageByLookupId(
     QueueHandle handle,
     long lookupId,
     LookupAction action,
     MQPROPS properties,
     NativeOverlapped *overlapped,
     ReceiveCallback receiveCallback,
     ITransaction transaction); //MSMQ internal transaction
Example #8
0
 /// <summary>
 /// Create a new websocket pointing to a server.
 /// </summary>
 /// <param name="url">Server URL</param>
 /// <param name="callback">Delegate to call when data is received</param>
 /// <param name="state">Optional object to pass to delegate</param>
 public Websocket(string url, ReceiveCallback callback, object state = null)
 {
     ws = new ClientWebSocket();
     ws.Options.SetBuffer(BufferSize, BufferSize);
     this.url   = url;
     this.rc   += callback;
     this.state = state;
 }
Example #9
0
 public unsafe static extern int ReceiveMessage(
     QueueHandle handle,
     uint timeout,
     ReadAction action,
     MQPROPS properties,
     NativeOverlapped *overlapped,
     ReceiveCallback receiveCallback,
     CursorHandle cursorHandle,
     ITransaction transaction); //MSMQ internal transaction
Example #10
0
 public IDisposable OnReceived(Func<byte[], object, Task> callback, object state)
 {
     var receiveCallback = new ReceiveCallback(callback, state);
     lock (_callbacks)
     {
         _callbacks.Add(receiveCallback);
     }
     return new Subscription(receiveCallback, _callbacks);
 }
 public NetworkPayload(Connection Connection, SyncObject syncObject, ReceiveCallback callback = null)
 {
     this.PacketSize     = Connection.HEADER_SIZE;
     this.Payload        = new byte[PacketSize];
     this.WriteOffset    = 0;
     this.ReceivedHeader = false;
     this.Callback       = callback;
     this.syncObject     = syncObject;
     this.Connection     = Connection;
     this.Header         = new PacketHeader(Connection);
 }
Example #12
0
        /// <summary>
        ///创建TCPRemote并ReceiveStart
        /// </summary>
        /// <returns></returns>
        public async Task <TcpRemote> ListenAsync(ReceiveCallback receiveHandle)
        {
            var remoteSocket = await Accept();

            var remote = new TcpRemote(remoteSocket);

            remote.MessagePipeline    = MessagePipeline.Default;
            remote.OnReceiveCallback += receiveHandle;
            remote.ReceiveStart();
            return(remote);
        }
        /// <summary>
        /// 创建TCPRemote并ReceiveStart.在ReceiveStart调用之前设置pipline,以免设置不及时漏掉消息.
        /// </summary>
        /// <param name="pipline"></param>
        /// <returns></returns>
        public async Task <TCPRemote> ListenAsync(ReceiveCallback receiveHandle, IMessagePipeline pipline)
        {
            var remoteSocket = await Accept();

            var remote = new TCPRemote(remoteSocket);

            remote.MessagePipeline    = pipline;
            remote.OnReceiveCallback += receiveHandle;
            remote.ReceiveStart();
            return(remote);
        }
Example #14
0
 private void SetReceiveCallback(ReceiveCallback cb)
 {
     if (false
         ==
         UUIRTSetReceiveCallback(DriverHandle,
                                 cb,
                                 IntPtr.Zero))
     {
         Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
     }
 }
Example #15
0
        ///////////// Methods for receiving //////////////////////


        /// <summary>
        /// We can read a string from the StringSocket by doing
        ///
        ///     ss.BeginReceive(callback, payload)
        ///
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, or
        /// failed in the attempt, it invokes the callback.  The parameters to the callback are
        /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
        /// string or the Exception will be non-null, but nor both.  If the string is non-null,
        /// it is the requested string (with the newline removed).  If the Exception is non-null,
        /// it is the Exception that caused the send attempt to fail.
        ///
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        ///
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        ///
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.
        /// </summary>
        /// <param name="callback"></param>
        /// <param name="payload"></param>
        public void BeginReceive(ReceiveCallback callback, object payload)
        {
            //Place the recieve request on the queue.
            receiveQueue.Enqueue(new ReceiveRequest(callback, payload));

            // For the first request start receving bytes otherwise we are already in the process.
            if (receiveQueue.Count == 1)
            {
                ReceiveBytes();
            }
        }
Example #16
0
        private void SetReceiveCallback(ReceiveCallback cb)
        {
            if (false == UUIRTSetReceiveCallback(_hDrvHandle, cb /*new ReceiveCallback(ReceiveCallbackProc)*/, IntPtr.Zero))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
//JLR Test
//			GC.Collect();
//			GC.WaitForPendingFinalizers();
//			GC.Collect();
//JLR Test
        }
Example #17
0
        /// <summary>
        /// We can read a string from the StringSocket by doing
        ///
        ///     ss.BeginReceive(callback, payload)
        ///
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, or
        /// failed in the attempt, it invokes the callback.  The parameters to the callback are
        /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
        /// string or the Exception will be non-null, but nor both.  If the string is non-null,
        /// it is the requested string (with the newline removed).  If the Exception is non-null,
        /// it is the Exception that caused the send attempt to fail.
        ///
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        ///
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        ///
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.
        ///
        /// <param name="callback"> The function to call upon receiving the data</param>
        /// <param name="payload">
        /// The payload is "remembered" so that when the callback is invoked, it can be associated
        /// with a specific Begin Receiver....
        /// </param>
        ///
        /// <example>
        ///   Here is how you might use this code:
        ///   <code>
        ///                    client = new TcpClient("localhost", port);
        ///                    Socket       clientSocket = client.Client;
        ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
        ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
        ///
        ///   </code>
        /// </example>
        /// </summary>
        public void BeginReceive(ReceiveCallback callback, object payload)
        {
            // Store the receive request, with its specified callback and payload.
            ReceiveRequest receiveRequest = new ReceiveRequest(callback, payload);

            ReceiveQueue.Enqueue(receiveRequest);

            // Ask the socket to call MessageReceive as soon as up to 1024 bytes arrive.
            byte[] buffer = new byte[1024];//this should work when this is set to a small number
            socket.BeginReceive(buffer, 0, buffer.Length,
                                SocketFlags.None, MessageReceived, buffer);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="serialPortName">Serial port name (e.g. COM1)</param>
 /// <param name="receiveCallback">Optional callback method to process incoming data.</param>
 public SerialComm(string serialPortName, ReceiveCallback receiveCallback = null)
 {
     if (receiveCallback != null)
     {
         DataReceived += receiveCallback;
     }
     // Set up the serial port
     Port = new SerialPort(serialPortName, 115200, Parity.None, 8, StopBits.One)
     {
         Handshake = Handshake.None
     };
     Port.DataReceived += PortHandler;
 }
Example #19
0
 /// <summary>
 ///
 /// <para>
 /// We can read a string from the StringSocket by doing
 /// </para>
 ///
 /// <para>
 ///     ss.BeginReceive(callback, payload)
 /// </para>
 ///
 /// <para>
 /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
 /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
 /// string of text terminated by a newline character from the underlying Socket, or
 /// failed in the attempt, it invokes the callback.  The parameters to the callback are
 /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
 /// string or the Exception will be non-null, but not both.  If the string is non-null,
 /// it is the requested string (with the newline removed).  If the Exception is non-null,
 /// it is the Exception that caused the send attempt to fail.
 /// </para>
 ///
 /// <para>
 /// This method is non-blocking.  This means that it does not wait until a line of text
 /// has been received before returning.  Instead, it arranges for a line to be received
 /// and then returns.  When the line is actually received (at some time in the future), the
 /// callback is called on another thread.
 /// </para>
 ///
 /// <para>
 /// This method is thread safe.  This means that multiple threads can call BeginReceive
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginReceive must taken care of synchronization instead.  On a given StringSocket, each
 /// arriving line of text must be passed to callbacks in the order in which the corresponding
 /// BeginReceive call arrived.
 /// </para>
 ///
 /// <para>
 /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
 /// even when there are no pending callbacks.  StringSocket implementations should refrain
 /// from buffering an unbounded number of incoming bytes beyond what is required to service
 /// the pending callbacks.
 /// </para>
 ///
 /// <param name="callback"> The function to call upon receiving the data</param>
 /// <param name="payload">
 /// The payload is "remembered" so that when the callback is invoked, it can be associated
 /// with a specific Begin Receiver....
 /// </param>
 ///
 /// <example>
 ///   Here is how you might use this code:
 ///   <code>
 ///                    client = new TcpClient("localhost", port);
 ///                    Socket       clientSocket = client.Client;
 ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
 ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
 ///
 ///   </code>
 /// </example>
 /// </summary>
 ///
 ///
 public void BeginReceive(ReceiveCallback callback, object payload)
 {
     lock (recKey)
     {
         //enque a new receive interaction
         receives.Enqueue(new RecInteraction(callback, payload));
         //if the que of receives has stuff, we need to check the incoming string
         if (receives.Count == 1)
         {
             CheckIncoming();
         }
     }
 }
Example #20
0
 public SocketWrap(
     ConnectCallback ccb,
     ListenCallback lcb,
     ReceiveCallback rcb,
     DisconnectCallback dcb,
     ErrorCallback ecb)
 {
     _ccb = ccb;
     _rcb = rcb;
     _ecb = ecb;
     _lcb = lcb;
     _dcb = dcb;
     _recvBuf = new byte[1024];
 }
Example #21
0
        /// <summary>
        /// Creates a new UsbUirt Controller.
        /// </summary>
        /// <remarks>In order to ensure that the connection with the USBUirt device is closed,
        /// you must call Dispose() when you are done with object.</remarks>
        public Controller()
        {
            _learnStates = new Hashtable();
            _hDrvHandle = OpenDriver();

            UUINFO uuInfo = GetVersion();
            _firmwareDate = new DateTime(2000 + uuInfo.fwDateYear, uuInfo.fwDateMonth, uuInfo.fwDateDay);
            _firmwareVersion = uuInfo.fwVersion;
            _protocolVersion = uuInfo.protVersion;

            #if false
            myCb = new ReceiveCallback(ReceiveCallbackProc);
            SetReceiveCallback(myCb);
            #endif
        }
Example #22
0
 /// <summary>
 /// We can read a string from the StringSocket by doing
 ///
 ///     ss.BeginReceive(callback, payload)
 ///
 /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
 /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
 /// string of text terminated by a newline character from the underlying Socket, or
 /// failed in the attempt, it invokes the callback.  The parameters to the callback are
 /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
 /// string or the Exception will be null, or possibly boh.  If the string is non-null,
 /// it is the requested string (with the newline removed).  If the Exception is non-null,
 /// it is the Exception that caused the send attempt to fail.  If both are null, this
 /// indicates that the sending end of the remote socket has been shut down.
 ///
 /// This method is non-blocking.  This means that it does not wait until a line of text
 /// has been received before returning.  Instead, it arranges for a line to be received
 /// and then returns.  When the line is actually received (at some time in the future), the
 /// callback is called on another thread.
 ///
 /// This method is thread safe.  This means that multiple threads can call BeginReceive
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
 /// arriving line of text must be passed to callbacks in the order in which the corresponding
 /// BeginReceive call arrived.
 ///
 /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
 /// even when there are no pending callbacks.  StringSocket implementations should refrain
 /// from buffering an unbounded number of incoming bytes beyond what is required to service
 /// the pending callbacks.
 /// </summary>
 public void BeginReceive(ReceiveCallback callback, object payload)
 {
     // Add the request to the queue, then start the receiving process if the queue
     // was previously empty.
     lock (receiveRequests)
     {
         receiveRequests.Enqueue(new ReceiveRequest {
             Callback = callback, Payload = payload
         });
         if (receiveRequests.Count == 1)
         {
             ProcessReceiveQueue();
         }
     }
 }
Example #23
0
        /// <summary>
        /// We can read a string from the StringSocket by doing
        ///
        ///     ss.BeginReceive(callback, payload)
        ///
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, or
        /// failed in the attempt, it invokes the callback.  The parameters to the callback are
        /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
        /// string or the Exception will be non-null, but nor both.  If the string is non-null,
        /// it is the requested string (with the newline removed).  If the Exception is non-null,
        /// it is the Exception that caused the send attempt to fail.
        ///
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        ///
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        ///
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.
        ///
        /// <param name="callback"> The function to call upon receiving the data</param>
        /// <param name="payload">
        /// The payload is "remembered" so that when the callback is invoked, it can be associated
        /// with a specific Begin Receiver....
        /// </param>
        ///
        /// <example>
        ///   Here is how you might use this code:
        ///   <code>
        ///                    client = new TcpClient("localhost", port);
        ///                    Socket       clientSocket = client.Client;
        ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
        ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
        ///
        ///   </code>
        /// </example>
        /// </summary>
        public void BeginReceive(ReceiveCallback callback, object payload)
        {
            // Protect the ReceiveQueue
            lock (ReceiveQueue)
            {
                // Create and store the receive request.
                ReceiveRequest receiveRequest = new ReceiveRequest(callback, payload);
                ReceiveQueue.Enqueue(receiveRequest);

                // If there is no receive ongoing, start receiving.
                if (ReceiveQueue.Count == 1)
                {
                    ProcessReceivedMessage();
                }
            }
        }
Example #24
0
        private void ProcessReceive(object sender, SocketAsyncEventArgs e)
        {
            logger?.Info($"Session.ProcessReceive: this={GetHashCode()}, e.SocketError={e?.SocketError}");

            if (e.SocketError == SocketError.Success && 0 < e.BytesTransferred)
            {
                ReceiveCallback?.Invoke(sender, new SessionEventArgs {
                    Text = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred), BytesTransferred = e.BytesTransferred
                });
                StartReceive();
            }
            else
            {
                CloseSocket(e);
            }
        }
Example #25
0
        /// <summary>
        ///     Creates a new UsbUirt Controller.
        /// </summary>
        /// <remarks>
        ///     In order to ensure that the connection with the USBUirt device is closed,
        ///     you must call Dispose() when you are done with object.
        /// </remarks>
        public Controller()
        {
            _learnStates = new Hashtable();
            _hDrvHandle  = OpenDriver();

            UUINFO uuInfo = GetVersion();

            _firmwareDate    = new DateTime(2000 + uuInfo.fwDateYear, uuInfo.fwDateMonth, uuInfo.fwDateDay);
            _firmwareVersion = uuInfo.fwVersion;
            _protocolVersion = uuInfo.protVersion;

#if false
            myCb = new ReceiveCallback(ReceiveCallbackProc);
            SetReceiveCallback(myCb);
#endif
        }
Example #26
0
 /// <summary>
 /// We can read a string from the StringSocket by doing
 ///
 ///     ss.BeginReceive(callback, payload)
 ///
 /// where callback is a ReceiveCallback (see above) and payload is an arbitrary object.
 /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
 /// string of text terminated by a newline character from the underlying Socket, or
 /// failed in the attempt, it invokes the callback.  The parameters to the callback are
 /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
 /// string or the Exception will be null, or possibly boh.  If the string is non-null,
 /// it is the requested string (with the newline removed).  If the Exception is non-null,
 /// it is the Exception that caused the send attempt to fail.  If both are null, this
 /// indicates that the sending end of the remote socket has been shut down.
 ///
 /// Alternatively, we can read a string from the StringSocket by doing
 ///
 ///     ss.BeginReceive(callback, payload, length)
 ///
 /// If length is negative or zero, this behaves identically to the first case.  If length
 /// is length, then instead of sending the next complete line in the callback, it sends
 /// the next length characters.  In other respects, it behaves analogously to the first case.
 ///
 /// This method is non-blocking.  This means that it does not wait until a line of text
 /// has been received before returning.  Instead, it arranges for a line to be received
 /// and then returns.  When the line is actually received (at some time in the future), the
 /// callback is called on another thread.
 ///
 /// This method is thread safe.  This means that multiple threads can call BeginReceive
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
 /// arriving line of text must be passed to callbacks in the order in which the corresponding
 /// BeginReceive call arrived.
 ///
 /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
 /// even when there are no pending callbacks.  StringSocket implementations should refrain
 /// from buffering an unbounded number of incoming bytes beyond what is required to service
 /// the pending callbacks.
 /// </summary>
 public void BeginReceive(ReceiveCallback callback, object payload, int length = 0)
 {
     lock (receiveQueue)
     {
         receiveQueue.Enqueue(new ReceiveRequest()
         {
             ReceiveBack = callback,
             Payload     = payload
         });
         if (receiveQueue.Count != 1)
         {
             return;
         }
         HandleReceiveQueue();
     }
 }
Example #27
0
        public void StartServer(IPAddress ip, int port, SocketAcceptCallback socketaccept = null, SocketLostCallback socketLost = null, ListenErrorCallback listenError = null, ReceiveCallback receive = null, SendBefore send = null, ListenCallback listen = null)
        {
            _ip   = ip;
            _port = port;
            _socketaccpetcallback = socketaccept;
            _socketLostCallback   = socketLost;
            _receivecallback      = receive;
            _sendBefore           = send;
            _listenCallback       = listen;
            _listenErrorCallback  = listenError;

            var listenThread = new Thread(Listen);

            listenThread.IsBackground = true;
            listenThread.Start();
        }
Example #28
0
        /// <summary>
        /// Called when some data has been received.
        /// </summary>
        private void ReceiveAsync(IAsyncResult result)
        {
            // Figure out how many bytes have come in
            int bytesRead = socket.EndReceive(result);
            // Convert the bytes into characters and appending to incoming
            int charsRead = decoder.GetChars(incomingBytes, 0, bytesRead, incomingChars, 0, false);

            incomingString.Append(incomingChars, 0, charsRead);
            int lastNewline = -1;
            int start       = 0;

            for (int i = 0; i < incomingString.Length; i++)
            {
                if (incomingString[i] == '\n')
                {
                    String line = incomingString.ToString(start, i - start);
                    // Pops the callback off the queue and gives it the proper line and payload.


                    lock (receiveLock)
                    {
                        ReceiveCallback returncallback = ReceiveQueue.Dequeue();
                        object          returnpayload  = ReceivePayLoadQueue.Dequeue();

                        Task task = new Task(() => returncallback(line, returnpayload));
                        task.Start();

                        //returncallback(line, returnpayload);
                    }


                    lastNewline = i;
                    start       = i + 1;
                }
            }

            incomingString.Remove(0, lastNewline + 1);
            //If the recieve queue has more callbacks in it then it needs to keep reading until all the recieve calls are complete.
            if (ReceiveQueue.Count != 0)
            {
                socket.BeginReceive(incomingBytes, 0, incomingBytes.Length, SocketFlags.None, ReceiveAsync, null);
            }
            else
            {
                ReceiveOngoing = false;
            }
        }
Example #29
0
        private bool disposedValue = false; // To detect redundant calls

        /// <summary>
        /// Dispose Websocket
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                    rc = null;
                    ws.Dispose();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
Example #30
0
 public MainForm()
 {
     //
     // The InitializeComponent() call is required for Windows Forms designer support.
     //
     InitializeComponent();
     //StartServer(49210);
     dsrv = new DataServer(49210);
     ReceiveCallback st = new ReceiveCallback(process);
     dsrv.ClientReceiveCallback = st;
     dsrv.Start();
     putMessage = new MessageDelegate(PutMessage);
     //
     // TODO: Add constructor code after the InitializeComponent() call.
     //
     //
 }
Example #31
0
        /// <summary>
        /// <para>
        /// We can read a string from the StringSocket by doing
        /// </para>
        ///
        /// <para>
        ///     ss.BeginReceive(callback, payload)
        /// </para>
        ///
        /// <para>
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, or
        /// failed in the attempt, it invokes the callback.  The parameters to the callback are
        /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
        /// string or the Exception will be non-null, but nor both.  If the string is non-null,
        /// it is the requested string (with the newline removed).  If the Exception is non-null,
        /// it is the Exception that caused the send attempt to fail.
        /// </para>
        ///
        /// <para>
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        /// </para>
        ///
        /// <para>
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        /// </para>
        ///
        /// <para>
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.
        /// </para>
        ///
        /// <param name="callback"> The function to call upon receiving the data</param>
        /// <param name="payload">
        /// The payload is "remembered" so that when the callback is invoked, it can be associated
        /// with a specific Begin Receiver....
        /// </param>
        ///
        /// <example>
        ///   Here is how you might use this code:
        ///   <code>
        ///                    client = new TcpClient("localhost", port);
        ///                    Socket       clientSocket = client.Client;
        ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
        ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
        ///
        ///   </code>
        /// </example>
        /// </summary>
        ///
        ///

        public void BeginReceive(ReceiveCallback callback, object payload)
        {
            lock (receiveQueue) // lock on to the receiveQueue (the lock object is arbitrary)
            {
                // create a new ReceiveMessage with the data and add it to the queue
                receiveQueue.Enqueue(new ReceiveMessage {
                    callback = callback, payload = payload
                });

                // if the second thread for processing receive message is not running,
                // then start a new thread to process the messages
                if (!isReceiving)
                {
                    isReceiving = true;
                    ReceiveNextMessage();
                }
            }
        }
Example #32
0
        /// <summary>
        /// We can read a string from the StringSocket by doing
        ///
        ///     ss.BeginReceive(callback, payload)
        ///
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, it
        /// invokes the callback.  The parameters to the callback are a string and the payload.
        /// The string is the requested string (with the newline removed).
        ///
        /// Alternatively, we can read a string from the StringSocket by doing
        ///
        ///     ss.BeginReceive(callback, payload, length)
        ///
        /// If length is negative or zero, this behaves identically to the first case.  If length
        /// is positive, then it reads and decodes length bytes from the underlying Socket, yielding
        /// a string s.  The parameters to the callback are s and the payload
        ///
        /// In either case, if there are insufficient bytes to service a request because the underlying
        /// Socket has closed, the callback is invoked with null and the payload.
        ///
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        ///
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        ///
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.
        /// </summary>
        public void BeginReceive(ReceiveCallback callback, object payload, int length = 0)
        {
            // Only locking here to make sure that the callback and its payload will always stay together.
            // If there is no lock then its possible that another entry could mess up our order in the queue.
            lock (receiveLock)
            {
                ReceiveQueue.Enqueue(callback);
                ReceivePayLoadQueue.Enqueue(payload);
                //LengthQueue.Enqueue(length);
            }

            if (ReceiveOngoing == false)
            {
                ReceiveOngoing = true;
                //Since we know we have a request for a string we can begin looking for it.
                socket.BeginReceive(incomingBytes, 0, incomingBytes.Length, SocketFlags.None, ReceiveAsync, null);
            }
        }
Example #33
0
        public void Receive(Json.Message message)
        {
            if (this.content.InvokeRequired)
            {
                ReceiveCallback r = new ReceiveCallback(Receive);
                this.Invoke(r, message);
                return;
            }
            else
            {
                msgqueued += 1;

                var sentTime = Clients.Utils.toDateTime(message.Timestamp);
                var user     = message.Username;
                var content  = message.Content;
                var append   = String.Format("\r\n{0} : {1}\r\n{2}\r\n", user, sentTime.ToString("MMM dd, hh:mm tt"), content);

                this.content.AppendText(append);
                FormTextRefresh();
            }
        }
Example #34
0
 /// <summary>
 /// We can read a string from the StringSocket by doing
 /// 
 ///     ss.BeginReceive(callback, payload)
 ///     
 /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
 /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
 /// string of text terminated by a newline character from the underlying Socket, or
 /// failed in the attempt, it invokes the callback.  The parameters to the callback are
 /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
 /// string or the Exception will be null, or possibly boh.  If the string is non-null, 
 /// it is the requested string (with the newline removed).  If the Exception is non-null, 
 /// it is the Exception that caused the send attempt to fail.  If both are null, this
 /// indicates that the sending end of the remote socket has been shut down.
 /// 
 /// This method is non-blocking.  This means that it does not wait until a line of text
 /// has been received before returning.  Instead, it arranges for a line to be received
 /// and then returns.  When the line is actually received (at some time in the future), the
 /// callback is called on another thread.
 /// 
 /// This method is thread safe.  This means that multiple threads can call BeginReceive
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
 /// arriving line of text must be passed to callbacks in the order in which the corresponding
 /// BeginReceive call arrived.
 /// 
 /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
 /// even when there are no pending callbacks.  StringSocket implementations should refrain
 /// from buffering an unbounded number of incoming bytes beyond what is required to service
 /// the pending callbacks.
 /// </summary>
 public void BeginReceive(ReceiveCallback callback, object payload)
 {
     // Add the request to the queue, then start the receiving process if the queue
     // was previously empty.
     lock (receiveRequests)
     {
         receiveRequests.Enqueue(new ReceiveRequest { Callback = callback, Payload = payload });
         if (receiveRequests.Count == 1)
         {
             ProcessReceiveQueue();
         }
     }
 }
Example #35
0
        public ReceiveHandler Send(Guid channelId, byte[] command, ReceiveCallback callback, int numOfPackagesToRec = 1)
        {
            var r = new ReceiveHandler();
            r.Callback = callback;
            r.ReceivePackageCount = numOfPackagesToRec;
            r.ChannelId = channelId;

            return Send(command, r);
        }
Example #36
0
 /// <summary>
 /// 
 /// <para>
 /// We can read a string from the StringSocket by doing
 /// </para>
 /// 
 /// <para>
 ///     ss.BeginReceive(callback, payload)
 /// </para>
 /// 
 /// <para>
 /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
 /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
 /// string of text terminated by a newline character from the underlying Socket, or
 /// failed in the attempt, it invokes the callback.  The parameters to the callback are
 /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
 /// string or the Exception will be non-null, but nor both.  If the string is non-null, 
 /// it is the requested string (with the newline removed).  If the Exception is non-null, 
 /// it is the Exception that caused the send attempt to fail.
 /// </para>
 /// 
 /// <para>
 /// This method is non-blocking.  This means that it does not wait until a line of text
 /// has been received before returning.  Instead, it arranges for a line to be received
 /// and then returns.  When the line is actually received (at some time in the future), the
 /// callback is called on another thread.
 /// </para>
 /// 
 /// <para>
 /// This method is thread safe.  This means that multiple threads can call BeginReceive
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
 /// arriving line of text must be passed to callbacks in the order in which the corresponding
 /// BeginReceive call arrived.
 /// </para>
 /// 
 /// <para>
 /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
 /// even when there are no pending callbacks.  StringSocket implementations should refrain
 /// from buffering an unbounded number of incoming bytes beyond what is required to service
 /// the pending callbacks.        
 /// </para>
 /// 
 /// <param name="callback"> The function to call upon receiving the data</param>
 /// <param name="payload"> 
 /// The payload is "remembered" so that when the callback is invoked, it can be associated
 /// with a specific Begin Receiver....
 /// </param>  
 /// 
 /// <example>
 ///   Here is how you might use this code:
 ///   <code>
 ///                    client = new TcpClient("localhost", port);
 ///                    Socket       clientSocket = client.Client;
 ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
 ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
 /// 
 ///   </code>
 /// </example>
 /// </summary>
 /// 
 /// 
 public void BeginReceive(ReceiveCallback callback, object payload)
 {
     lock (ReceiveLock)
     {
         ReceiveRequests.Enqueue(new ReceiveRequest{Callback = callback, Payload = payload});
         if (ReceiveRequests.Count == 1)
             ProcessReceive();
     }
 }
Example #37
0
        /// <summary>
        /// We can read a string from the StringSocket by doing
        /// 
        ///     ss.BeginReceive(callback, payload)
        ///     
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, or
        /// failed in the attempt, it invokes the callback.  The parameters to the callback are
        /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
        /// string or the Exception will be null, or possibly boh.  If the string is non-null, 
        /// it is the requested string (with the newline removed).  If the Exception is non-null, 
        /// it is the Exception that caused the send attempt to fail.  If both are null, this
        /// indicates that the sending end of the remote socket has been shut down.
        /// 
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        /// 
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        /// 
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.
        /// </summary>
        public void BeginReceive(ReceiveCallback callback, object payload, callbacks c)
        {
            // Add the request to the queue, then start the receiving process if the queue
            // was previously empty.
            lock (receiveRequests)
            {
                //if (c == callbacks.UPDATE)
                //{

                //    updateRequests.Enqueue(new ReceiveRequest { Callback = callback, Payload = payload, whichCB = c });

                //}
                //else if (c == callbacks.CHANGE)
                //{

                //    changeRequests.Enqueue(new ReceiveRequest { Callback = callback, Payload = payload, whichCB = c });

                //}
                //else
                    receiveRequests.Enqueue(new ReceiveRequest { Callback = callback, Payload = payload, whichCB = c });
                if (receiveRequests.Count == 1)
                {
                    ProcessReceiveQueue();
                }
            }
        }
Example #38
0
 public RecInteraction( ReceiveCallback _recvCb,object _payload)
 {
     payload = _payload;
     recvCB = _recvCb;
 }
 private static extern bool UUIRTSetReceiveCallback(
     IntPtr hDrvHandle,
     ReceiveCallback receiveProc,
     IntPtr userData);
Example #40
0
        /// <summary>
        /// We can read a string from the StringSocket by doing
        /// 
        ///     ss.BeginReceive(callback, payload)
        /// 
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, or
        /// failed in the attempt, it invokes the callback.  The parameters to the callback are
        /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
        /// string or the Exception will be non-null, but nor both.  If the string is non-null, 
        /// it is the requested string (with the newline removed).  If the Exception is non-null, 
        /// it is the Exception that caused the send attempt to fail.
        /// 
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        /// 
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        /// 
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.        
        /// 
        /// <param name="callback"> The function to call upon receiving the data</param>
        /// <param name="payload"> 
        /// The payload is "remembered" so that when the callback is invoked, it can be associated
        /// with a specific Begin Receiver....
        /// </param>  
        /// 
        /// <example>
        ///   Here is how you might use this code:
        ///   <code>
        ///                    client = new TcpClient("localhost", port);
        ///                    Socket       clientSocket = client.Client;
        ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
        ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
        /// 
        ///   </code>
        /// </example>
        /// </summary>
        public void BeginReceive(ReceiveCallback callback, object payload)
        {
            // Store the receive request, with its specified callback and payload.
            ReceiveRequest receiveRequest = new ReceiveRequest(callback, payload);
            ReceiveQueue.Enqueue(receiveRequest);

            // Ask the socket to call MessageReceive as soon as up to 1024 bytes arrive.
            byte[] buffer = new byte[1024];//this should work when this is set to a small number
            socket.BeginReceive(buffer, 0, buffer.Length,
                                SocketFlags.None, MessageReceived, buffer);
        }
Example #41
0
 /// <summary>
 /// We can read a string from the StringSocket by doing
 /// 
 ///     ss.BeginReceive(callback, payload)
 ///     
 /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
 /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
 /// string of text terminated by a newline character from the underlying Socket, or
 /// failed in the attempt, it invokes the callback.  The parameters to the callback are
 /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
 /// string or the Exception will be non-null, but nor both.  If the string is non-null, 
 /// it is the requested string (with the newline removed).  If the Exception is non-null, 
 /// it is the Exception that caused the send attempt to fail.
 /// 
 /// This method is non-blocking.  This means that it does not wait until a line of text
 /// has been received before returning.  Instead, it arranges for a line to be received
 /// and then returns.  When the line is actually received (at some time in the future), the
 /// callback is called on another thread.
 /// 
 /// This method is thread safe.  This means that multiple threads can call BeginReceive
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
 /// arriving line of text must be passed to callbacks in the order in which the corresponding
 /// BeginReceive call arrived.
 /// 
 /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
 /// even when there are no pending callbacks.  StringSocket implementations should refrain
 /// from buffering an unbounded number of incoming bytes beyond what is required to service
 /// the pending callbacks.
 /// </summary>
 public void BeginReceive(ReceiveCallback callback, object payload)
 {
     // create new dictionary and store callback and payload in it
     Dictionary<string, object> dict = new Dictionary<string, object>(2);
     dict.Add("callback", callback);
     dict.Add("payload", payload);
     receiveQueue.Enqueue(dict);
 }
Example #42
0
 public ReceiveRequest(ReceiveCallback cb, Object o)
 {
     receiveCallBack = cb;
     payload = o;
 }
Example #43
0
        /// <summary>
        /// We can read a string from the StringSocket by doing
        /// 
        ///     ss.BeginReceive(callback, payload)
        /// 
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, or
        /// failed in the attempt, it invokes the callback.  The parameters to the callback are
        /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
        /// string or the Exception will be non-null, but nor both.  If the string is non-null, 
        /// it is the requested string (with the newline removed).  If the Exception is non-null, 
        /// it is the Exception that caused the send attempt to fail.
        /// 
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        /// 
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        /// 
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.        
        /// 
        /// <param name="callback"> The function to call upon receiving the data</param>
        /// <param name="payload"> 
        /// The payload is "remembered" so that when the callback is invoked, it can be associated
        /// with a specific Begin Receiver....
        /// </param>  
        /// 
        /// <example>
        ///   Here is how you might use this code:
        ///   <code>
        ///                    client = new TcpClient("localhost", port);
        ///                    Socket       clientSocket = client.Client;
        ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
        ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
        /// 
        ///   </code>
        /// </example>
        /// </summary>
        public void BeginReceive(ReceiveCallback callback, object payload)
        {
            // Protect the ReceiveQueue
            lock (ReceiveQueue)
            {
                // Create and store the receive request.
                ReceiveRequest receiveRequest = new ReceiveRequest(callback, payload);
                ReceiveQueue.Enqueue(receiveRequest);

                // If there is no receive ongoing, start receiving.
                if (ReceiveQueue.Count == 1)
                {
                    ProcessReceivedMessage();
                }
            }
        }
Example #44
0
 private void SetReceiveCallback(ReceiveCallback cb)
 {
     if (false == UUIRTSetReceiveCallback(_hDrvHandle, cb/*new ReceiveCallback(ReceiveCallbackProc)*/, IntPtr.Zero)){
         Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
     }
     //JLR Test
     //			GC.Collect();
     //			GC.WaitForPendingFinalizers();
     //			GC.Collect();
     //JLR Test
 }
Example #45
0
 public ReceiveHandler Send(byte[] command, ReceiveCallback callback, int numOfPackagesToRec = 1)
 {
     return Send(default(Guid), command, callback,numOfPackagesToRec);
 }
 private void SetReceiveCallback(ReceiveCallback cb)
 {
     if (false
         ==
         UUIRTSetReceiveCallback(DriverHandle,
             cb,
             IntPtr.Zero))
     {
         Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
     }
 }
Example #47
0
        /// <summary>
        /// 
        /// <para>
        /// We can read a string from the StringSocket by doing
        /// </para>
        /// 
        /// <para>
        ///     ss.BeginReceive(callback, payload)
        /// </para>
        /// 
        /// <para>
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, or
        /// failed in the attempt, it invokes the callback.  The parameters to the callback are
        /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
        /// string or the Exception will be non-null, but nor both.  If the string is non-null, 
        /// it is the requested string (with the newline removed).  If the Exception is non-null, 
        /// it is the Exception that caused the send attempt to fail.
        /// </para>
        /// 
        /// <para>
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        /// </para>
        /// 
        /// <para>
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        /// </para>
        /// 
        /// <para>
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.        
        /// </para>
        /// 
        /// <param name="callback"> The function to call upon receiving the data</param>
        /// <param name="payload"> 
        /// The payload is "remembered" so that when the callback is invoked, it can be associated
        /// with a specific Begin Receiver....
        /// </param>  
        /// 
        /// <example>
        ///   Here is how you might use this code:
        ///   <code>
        ///                    client = new TcpClient("localhost", port);
        ///                    Socket       clientSocket = client.Client;
        ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
        ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
        /// 
        ///   </code>
        /// </example>
        /// </summary>
        public void BeginReceive(ReceiveCallback callback, object payload)
        {
            lock (lockReceive)
            {
                // Store it as a message.
                _messagesReceived.Enqueue(new Message(callback, payload));

                if (!_receiveParseIsOngoing)
                {
                    _receiveParseIsOngoing = true;
                    try
                    {
                        MessageReceived();
                    }
                    catch (Exception e)
                    {
                        _messageReceived.ReCallback(null, e, _messageReceived.Payload);
                    }
                }
            }
        }
Example #48
0
 /// <summary>
 /// 
 /// <para>
 /// We can read a string from the StringSocket by doing
 /// </para>
 /// 
 /// <para>
 ///     ss.BeginReceive(callback, payload)
 /// </para>
 /// 
 /// <para>
 /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
 /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
 /// string of text terminated by a newline character from the underlying Socket, or
 /// failed in the attempt, it invokes the callback.  The parameters to the callback are
 /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
 /// string or the Exception will be non-null, but not both.  If the string is non-null, 
 /// it is the requested string (with the newline removed).  If the Exception is non-null, 
 /// it is the Exception that caused the send attempt to fail.
 /// </para>
 /// 
 /// <para>
 /// This method is non-blocking.  This means that it does not wait until a line of text
 /// has been received before returning.  Instead, it arranges for a line to be received
 /// and then returns.  When the line is actually received (at some time in the future), the
 /// callback is called on another thread.
 /// </para>
 /// 
 /// <para>
 /// This method is thread safe.  This means that multiple threads can call BeginReceive
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginReceive must taken care of synchronization instead.  On a given StringSocket, each
 /// arriving line of text must be passed to callbacks in the order in which the corresponding
 /// BeginReceive call arrived.
 /// </para>
 /// 
 /// <para>
 /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
 /// even when there are no pending callbacks.  StringSocket implementations should refrain
 /// from buffering an unbounded number of incoming bytes beyond what is required to service
 /// the pending callbacks.        
 /// </para>
 /// 
 /// <param name="callback"> The function to call upon receiving the data</param>
 /// <param name="payload"> 
 /// The payload is "remembered" so that when the callback is invoked, it can be associated
 /// with a specific Begin Receiver....
 /// </param>  
 /// 
 /// <example>
 ///   Here is how you might use this code:
 ///   <code>
 ///                    client = new TcpClient("localhost", port);
 ///                    Socket       clientSocket = client.Client;
 ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
 ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
 /// 
 ///   </code>
 /// </example>
 /// </summary>
 /// 
 /// 
 public void BeginReceive(ReceiveCallback callback, object payload)
 {
     lock (recKey)
     {
         //enque a new receive interaction
         receives.Enqueue(new RecInteraction(callback, payload));
         //if the que of receives has stuff, we need to check the incoming string
         if (receives.Count == 1)
             CheckIncoming();
     }
 }