コード例 #1
0
        private void StartReceiving(Socket handler)
        {
            while (IsListening)
            {
                // Set the event to nonsignaled state.
                receiveDone.Reset();

                // Receive the response from the remote device.
                try
                {
                    // Create the state object.
                    StateObject state = new StateObject();
                    state.workSocket = handler;

                    // Begin receiving the data from the remote device.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                         new AsyncCallback(ReceiveCallback), state);
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(ex.ToString());
                    TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
                }

                receiveDone.WaitOne();
            }
        }
コード例 #2
0
        private void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                // Signal the main thread to continue.
                connectDone.Set();

                // Get the socket that handles the client request.
                Socket listener = (Socket)ar.AsyncState;

                Socket handler = listener.EndAccept(ar);

                // 加入 Client 清單
                Socket socket = null;
                _clients.TryRemove(handler.LocalEndPoint.ToString(), out socket);
                _clients.TryAdd(handler.LocalEndPoint.ToString(), handler);

                // Create the state object.
                //StateObject state = new StateObject();
                //state.workSocket = handler;
                //handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                //    new AsyncCallback(ReadCallback), state);
                StartReceiving(handler);
            }
            catch (ObjectDisposedException)
            {
                // 順利關閉
            }
            catch (Exception ex)
            {
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #3
0
        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete the connection.
                client.EndConnect(ar);

                // Signal that the connection has been made.
                connectDone.Set();

                //Console.WriteLine("Socket connected to {0}",
                //    client.RemoteEndPoint.ToString());
                TriggerConnectionStatus(true);
            }
            catch (Exception ex)
            {
                // Signal that the connection has been made.
                connectDone.Set();

                //Console.WriteLine(ex.ToString());
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #4
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state  = (StateObject)ar.AsyncState;
                Socket      client = state.workSocket;

                // 斷線時, 也會觸發此事件
                if (client.Connected == false)
                {
                    receiveDone.Set();
                    //MessageReceived?.Invoke(this, new SocketMessageEventArgs("Disconnected"));
                    return;
                }

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read
                    // more data.
                    response = state.sb.ToString();
                    if (response.IndexOf("<EOF>") > -1)
                    {
                        // Signal that all bytes have been received.
                        receiveDone.Set();

                        //// All the data has been read from the
                        //// client. Display it on the console.
                        MessageReceived?.Invoke(this, new SocketMessageEventArgs(response));
                    }
                    else
                    {
                        // Get the rest of the data.
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                            new AsyncCallback(ReceiveCallback), state);
                    }
                }
            }
            catch (Exception ex)
            {
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #5
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                string content = string.Empty;

                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                StateObject state   = (StateObject)ar.AsyncState;
                Socket      handler = state.workSocket;

                // Read data from the client socket.
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read
                    // more data.
                    content = state.sb.ToString();
                    if (content.IndexOf("<EOF>") > -1)
                    {
                        // Signal that all bytes have been received.
                        receiveDone.Set();

                        //// All the data has been read from the
                        //// client. Display it on the console.
                        //Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                        //    content.Length, content);
                        //// Echo the data back to the client.
                        //Send(handler, content);
                        //Send(handler, "received");
                        MessageReceived?.Invoke(this, new SocketMessageEventArgs(content));
                    }
                    else
                    {
                        // Not all data received. Get more.
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                             new AsyncCallback(ReceiveCallback), state);
                    }
                }
            }
            catch (Exception ex)
            {
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #6
0
ファイル: KtMmfEventBus.cs プロジェクト: DevTainan/KTCommon
 public KtMmfEventBus()
 {
     _timer           = new KtTimer(double.Epsilon, ReceiveData);
     _timer.Starting += (object sender, EventArgs e) =>
     {
         ConnectionStatus?.Invoke(this, new ConnectionStatusEventArgs(true));
     };
     _timer.Stopped += (object sender, EventArgs e) =>
     {
         ConnectionStatus?.Invoke(this, new ConnectionStatusEventArgs(false));
     };
     _timer.Error += (object sender, ExceptionEventArgs e) =>
     {
         TransactionError?.Invoke(this, e);
     };
 }
コード例 #7
0
ファイル: KTAppEventBus.cs プロジェクト: DevTainan/KTCommon
 private KTAppEventBus()
 {
     _queue           = new ConcurrentQueue <EventBusMessageEventArgs>();
     _timer           = new KtTimer(50, ProcessQueue);
     _timer.Starting += (object sender, EventArgs e) =>
     {
         ConnectionStatus?.Invoke(this, new ConnectionStatusEventArgs(true));
     };
     _timer.Stopped += (object sender, EventArgs e) =>
     {
         ConnectionStatus?.Invoke(this, new ConnectionStatusEventArgs(false));
     };
     _timer.Error += (object sender, ExceptionEventArgs e) =>
     {
         TransactionError?.Invoke(this, e);
     };
 }
コード例 #8
0
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to client.", bytesSent);

                //handler.Shutdown(SocketShutdown.Both);
                //handler.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #9
0
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);
                //Console.WriteLine("Sent {0} bytes to server.", bytesSent);

                // Signal that all bytes have been sent.
                //sendDone.Set();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #10
0
        public void Disconnect()
        {
            if (IsListening == false)
            {
                return;
            }

            TriggerConnectionStatus(false); //先變更 IsConnected 屬性, 停止背景的監聽

            // Release the socket.
            try
            {
                //_listener.Shutdown(SocketShutdown.Both);
                _listener.Close();
            }
            catch (SocketException ex)
            {
                string temp = ex.ToString();
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
コード例 #11
0
        public void Connect()
        {
            if (IsListening)
            {
                return;
            }

            // Establish the local endpoint for the socket.
            // The DNS name of the computer
            // running the listener is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.GetHostEntry(_ip);
            //IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress  ipAddress     = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, _port);

            // Create a TCP/IP socket.
            _listener = new Socket(ipAddress.AddressFamily,
                                   SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                _listener.Bind(localEndPoint);
                _listener.Listen(100);

                TriggerConnectionStatus(true);

                Task.Factory.StartNew(StartListing);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }

            //Console.WriteLine("\nPress ENTER to continue...");
            //Console.Read();
        }
コード例 #12
0
ファイル: KtMmfEventBus.cs プロジェクト: DevTainan/KTCommon
        public void Send(string channelId, string messageId, string content)
        {
            try
            {
                bool mutexCreated = false;
                using (Mutex mutex = new Mutex(true, "KtMmfEventBus", out mutexCreated))
                {
                    using (MemoryMappedViewStream stream = _mmf.CreateViewStream(WriteOffset, _size))
                    {
                        BinaryWriter writer = new BinaryWriter(stream);
                        writer.Write(DateTime.UtcNow.Ticks);
                        writer.Write(channelId);
                        writer.Write(messageId);
                        writer.Write(content);
                    }

                    mutex.ReleaseMutex();
                }
            }
            catch (Exception ex)
            {
                TransactionError?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }