예제 #1
0
    public void StartListening(String host, int port, OnReceive on_receive, OnConnect on_connect, OnDisconnect on_disconnect, OnListenError on_listen_error)
    {
        on_receive_      = on_receive;
        on_connect_      = on_connect;
        on_disconnect_   = on_disconnect;
        on_listen_error_ = on_listen_error;
        size_receiving_  = 0;
        IPAddress ipAddress = IPAddress.Parse(GetIPAddress(host));

        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

        // Create a TCP/IP socket.
        listener_ = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listener_.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

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

            // Start an asynchronous socket to listen for connections.
            listener_.BeginAccept(new AsyncCallback(AcceptCallback), listener_);
        }
        catch (Exception e)
        {
            on_listen_error_(e.ToString());
        }
    }
예제 #2
0
        /// <summary>
        /// receive an event targeted to this particular player
        /// </summary>
        /// <param name="post"></param>
        static void ListenForMessages()
        {
            _isRunning = true;
            var listener = new ServiceBusListener();

            while (_shouldRun)
            {
                try
                {
                    listener.ListenForMessages();
                }
                catch (WebException ex)
                {
                    // if the server has not created a topic yet for the client then a 404 error will be returned so do not report
                    if (!ex.Message.Contains("The remote server returned an error: (404) Not Found"))
                    {
                        if (OnListenError != null)
                        {
                            OnListenError.Invoke(null, new ErrorEventArgs(ex));
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (OnListenError != null)
                    {
                        OnListenError.Invoke(null, new ErrorEventArgs(ex));
                    }
                }
            }

            _isRunning = false;
        }
예제 #3
0
        static void ReadCallBack(IAsyncResult asyncResult)
        {
            try
            {
                // Get the RequestState object from AsyncResult.
                RequestState rs = (RequestState)asyncResult.AsyncState;

                // Retrieve the ResponseStream that was set in RespCallback.
                Stream responseStream = rs.ResponseStream;

                // Read rs.BufferRead to verify that it contains data.
                int read = responseStream.EndRead(asyncResult);
                if (read > 0)
                {
                    // Prepare a Char array buffer for converting to Unicode.
                    Char[] charBuffer = new Char[BUFFER_SIZE];

                    // Convert byte stream to Char array and then to String.
                    // len contains the number of characters converted to Unicode.
                    rs.StreamDecode.GetChars(rs.BufferRead, 0, read, charBuffer, 0);

                    // Append the recently read data to the RequestData stringbuilder
                    // object contained in RequestState.
                    rs.RequestData.Append(
                        Encoding.ASCII.GetString(rs.BufferRead, 0, read));

                    // Continue reading data until
                    // responseStream.EndRead returns –1.
                    responseStream.BeginRead(rs.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);
                }
                else
                {
                    if (rs.RequestData.Length > 0)
                    {
                        HandlePacket(rs.RequestData.ToString());
                    }
                    // Close down the response stream.
                    responseStream.Close();
                    // Set the ManualResetEvent so the main thread can exit.
                    allDone.Set();
                }
            }
            catch (Exception ex)
            {
                if (OnListenError != null)
                {
                    OnListenError.Invoke(null, new ErrorEventArgs(ex));
                }
            }

            return;
        }
예제 #4
0
        public void ListenForMessages()
        {
            if (_isRunning != null && !_isRunning.IsCompleted)
            {
                return;
            }

            var address = new Uri(CommonConfiguration.Instance.BackboneConfiguration.GetServiceSubscriptionsAddress(Queue, CommonConfiguration.Instance.PlayerId));

            try
            {
                WebRequest request = WebRequest.Create(address);

                if (_sasProvider == null)
                {
                    _sasProvider = new SharedAccessSignatureTokenProvider(CommonConfiguration.Instance.BackboneConfiguration.IssuerName,
                                                                          CommonConfiguration.Instance.BackboneConfiguration.IssuerSecret,
                                                                          new TimeSpan(1, 0, 0));
                }

                var token = _sasProvider.GetToken(CommonConfiguration.Instance.BackboneConfiguration.GetRealm(), "POST", new TimeSpan(1, 0, 0));
                request.Headers[HttpRequestHeader.Authorization] = token.TokenValue;
                request.Method = "DELETE";
                RequestState rs = new RequestState();
                rs.Request = request;

                _isRunning = request.BeginGetResponse(new AsyncCallback(RespCallback), rs);
            }
            catch (WebException ex)
            {
                // if the server has not created a topic yet for the client then a 404 error will be returned so do not report
                if (!ex.Message.Contains("The remote server returned an error: (404) Not Found"))
                {
                    if (OnListenError != null)
                    {
                        OnListenError.Invoke(this, new System.IO.ErrorEventArgs(ex));
                    }
                }
            }
            catch (Exception ex)
            {
                if (OnListenError != null)
                {
                    OnListenError.Invoke(this, new System.IO.ErrorEventArgs(ex));
                }
            }
        }
예제 #5
0
        private static void RespCallback(IAsyncResult ar)
        {
            try
            {
                // Get the RequestState object from the async result.
                RequestState rs = (RequestState)ar.AsyncState;

                // Get the WebRequest from RequestState.
                WebRequest req = rs.Request;

                // Call EndGetResponse, which produces the WebResponse object
                //  that came from the request issued above.
                WebResponse resp = req.EndGetResponse(ar);

                //  Start reading data from the response stream.
                Stream ResponseStream = resp.GetResponseStream();

                // Store the response stream in RequestState to read
                // the stream asynchronously.
                rs.ResponseStream = ResponseStream;

                //  Pass rs.BufferRead to BeginRead. Read data into rs.BufferRead
                IAsyncResult iarRead = ResponseStream.BeginRead(rs.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);

                if (iarRead.IsCompleted != true)
                {
                    Debug.LogWarning("ServiceBusListener.RespCallback() invalid read.");
                }
            }
            catch (Exception ex)
            {
                if (OnListenError != null)
                {
                    OnListenError.Invoke(null, new ErrorEventArgs(ex));
                }
            }
        }