コード例 #1
0
        private static bool GetInvokerForHash(int cmdHash, UNetInvokeType invokeType, out Type invokeClass, out CmdDelegate invokeFunction)
        {
            bool result;

            if (!s_CmdHandlerDelegates.TryGetValue(cmdHash, out var invoker))
            {
                QLog.Error($"GetInvokerForHash hash:{cmdHash} not found");
                invokeClass    = null;
                invokeFunction = null;
                result         = false;
            }
            else if (invoker == null)
            {
                QLog.Error($"GetInvokerForHash hash:{cmdHash} invoker null");
                invokeClass    = null;
                invokeFunction = null;
                result         = false;
            }
            else if (invoker.invokeType != invokeType)
            {
                QLog.Error($"GetInvokerForHash hash:{cmdHash} mismatched invokeType");
                invokeClass    = null;
                invokeFunction = null;
                result         = false;
            }
            else
            {
                invokeClass    = invoker.invokeClass;
                invokeFunction = invoker.invokeFunction;
                result         = true;
            }
            return(result);
        }
コード例 #2
0
 private void FinishLoadScene()
 {
     if (client != null)
     {
         if (s_ClientReadyConnection != null)
         {
             clientLoadedScene = true;
             OnClientConnect(s_ClientReadyConnection);
             s_ClientReadyConnection = null;
         }
     }
     else
     {
         QLog.Error("FinishLoadScene client is null");
     }
     if (QNetworkServer.active)
     {
         QNetworkServer.SpawnObjects();
         OnServerSceneChanged(networkSceneName);
     }
     if (IsClientConnected() && client != null)
     {
         RegisterClientMessages(client);
         OnClientSceneChanged(client.connection);
     }
 }
コード例 #3
0
 protected void HandleReader(QNetworkReader reader, int receivedSize, int channelId)
 {
     while (reader.Position < receivedSize)
     {
         var num     = reader.ReadUInt16();
         var num2    = reader.ReadInt16();
         var array   = reader.ReadBytes(num);
         var reader2 = new QNetworkReader(array);
         QNetworkMessageDelegate networkMessageDelegate = null;
         if (m_MessageHandlersDict.ContainsKey(num2))
         {
             networkMessageDelegate = m_MessageHandlersDict[num2];
         }
         if (networkMessageDelegate == null)
         {
             QLog.Error($"Unknown message ID {num2} connId:{connectionId}");
             break;
         }
         m_NetMsg.MsgType    = num2;
         m_NetMsg.Reader     = reader2;
         m_NetMsg.Connection = this;
         m_NetMsg.ChannelId  = channelId;
         networkMessageDelegate(m_NetMsg);
         lastMessageTime = Time.time;
     }
 }
コード例 #4
0
 public virtual void OnServerDisconnect(QNetworkConnection conn)
 {
     QNetworkServer.DestroyPlayersForConnection(conn);
     if (conn.LastError != NetworkError.Ok)
     {
         QLog.Error($"ServerDisconnected due to error: {conn.LastError}");
     }
 }
コード例 #5
0
 public virtual void OnClientDisconnect(QNetworkConnection conn)
 {
     StopClient();
     if (conn.LastError != NetworkError.Ok)
     {
         QLog.Error($"ClientDisconnected due to error: {conn.LastError}");
     }
 }
コード例 #6
0
        public void StartHandleResponseBody(Stream inputStream, EndResponseBody endResponseBody)
        {
            ResponseBodyState responseBodyState = new ResponseBodyState();

            responseBodyState.inputStream     = inputStream;
            responseBodyState.endResponseBody = endResponseBody;
            responseBodyState.completed       = 0L;

            try
            {
                int count = (int)((contentLength > SEGMENT_SIZE || contentLength <= 0) ? SEGMENT_SIZE : contentLength);

                byte[] buffer = new byte[count];

                responseBodyState.buffer = buffer;

                if (isDownload)
                {
                    if (File.Exists(filePath) && new FileInfo(filePath).Length > fileOffset)
                    {
                        // 写脏文件了,直接 Truncate
                        fileStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write);
                    }
                    else
                    {
                        // 正常文件或者追加写场景,直接写入
                        fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
                    }
                    fileStream.Seek(fileOffset, SeekOrigin.Begin);
                    responseBodyState.inputStream.BeginRead(responseBodyState.buffer, 0, responseBodyState.buffer.Length, AsyncStreamCallback, responseBodyState);
                }
                else
                {
                    memoryStream             = new MemoryStream(count);
                    responseBodyState.buffer = buffer;
                    responseBodyState.inputStream.BeginRead(responseBodyState.buffer, 0, responseBodyState.buffer.Length, AsyncStreamCallback, responseBodyState);
                }
            }
            catch (Exception ex)
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }

                if (memoryStream != null)
                {
                    memoryStream.Close();
                    memoryStream.Dispose();
                }

                responseBodyState.endResponseBody(false, ex);
                responseBodyState.Clear();

                QLog.Error("ResponseBody", ex.Message, ex);
            }
        }
コード例 #7
0
 protected void SendEventInternal(QNetworkWriter writer, int channelId, string eventName)
 {
     if (!QNetworkServer.active)
     {
         QLog.Error($"Tried to send event {eventName} on channel {channelId} but QSBNetworkServer isn't active.");
         return;
     }
     writer.FinishMessage();
     QNetworkServer.SendWriterToReady(gameObject, writer, channelId);
 }
コード例 #8
0
 public QNetworkClient StartClient(ConnectionConfig config, int hostPort)
 {
     InitializeSingleton();
     if (runInBackground)
     {
         Application.runInBackground = true;
     }
     isNetworkActive = true;
     if (m_GlobalConfig != null)
     {
         NetworkTransport.Init(m_GlobalConfig);
     }
     client = new QNetworkClient
     {
         hostPort = hostPort
     };
     if (config != null)
     {
         if (config.UsePlatformSpecificProtocols && Application.platform != RuntimePlatform.PS4 && Application.platform != RuntimePlatform.PSP2)
         {
             throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform");
         }
         client.Configure(config, 1);
     }
     else if (customConfig && m_ConnectionConfig != null)
     {
         m_ConnectionConfig.Channels.Clear();
         foreach (var channel in channels)
         {
             m_ConnectionConfig.AddChannel(channel);
         }
         if (m_ConnectionConfig.UsePlatformSpecificProtocols && Application.platform != RuntimePlatform.PS4 && Application.platform != RuntimePlatform.PSP2)
         {
             throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform");
         }
         client.Configure(m_ConnectionConfig, maxConnections);
     }
     RegisterClientMessages(client);
     if (string.IsNullOrEmpty(networkAddress))
     {
         QLog.Error("Must set the Network Address field in the manager");
         return(null);
     }
     if (useSimulator)
     {
         client.ConnectWithSimulator(networkAddress, networkPort, simulatedLatency, packetLossPercentage);
     }
     else
     {
         client.Connect(networkAddress, networkPort);
     }
     OnStartClient(client);
     s_Address = networkAddress;
     return(client);
 }
コード例 #9
0
 internal void RemovePlayerController(short playerControllerId)
 {
     for (var i = PlayerControllers.Count; i >= 0; i--)
     {
         if (playerControllerId == i && playerControllerId == PlayerControllers[i].PlayerControllerId)
         {
             PlayerControllers[i] = new QPlayerController();
             return;
         }
     }
     QLog.Error($"RemovePlayer player at playerControllerId {playerControllerId} not found");
 }
コード例 #10
0
        /// <summary>
        /// async to excute
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="config"></param>
        public static void Schedue(Request request, Response response, HttpClientConfig config)
        {
            HttpWebRequest httpWebRequest = null;
            RequestState   requestState   = new RequestState();

            try
            {
                requestState.request = request;

                requestState.response = response;

                httpWebRequest = WebRequest.Create(request.RequestUrlString) as HttpWebRequest;

                httpWebRequest.AllowWriteStreamBuffering = false;

                //bind webRequest
                request.BindHttpWebRequest(httpWebRequest);

                //handle request header
                HandleHttpWebRequestHeaders(request, httpWebRequest, config);

                requestState.httpWebRequest = httpWebRequest;

                //handle request body
                if (request.Body != null)
                {
                    httpWebRequest.ContentLength = request.Body.ContentLength;
                    httpWebRequest.BeginGetRequestStream(new AsyncCallback(AsyncRequestCallback), requestState);
                }
                else
                {
                    //wait for response
                    httpWebRequest.BeginGetResponse(new AsyncCallback(AsyncResponseCallback), requestState);
                }

                //print log
                PrintReqeustInfo(httpWebRequest);
            }
            catch (WebException webEx)
            {
                response.OnFinish(false, webEx);
                //abort
                requestState.Clear();
                QLog.Debug(TAG, webEx.Message, webEx);
            }
            catch (Exception ex)
            {
                response.OnFinish(false, ex);
                //abort
                requestState.Clear();
                QLog.Error(TAG, ex.Message, ex);
            }
        }
コード例 #11
0
 public override string GetMD5()
 {
     try
     {
         fileStream.Seek(fileOffset, SeekOrigin.Begin);
         return(DigestUtils.GetMd5ToBase64(fileStream, contentLength));
     }
     catch (Exception ex)
     {
         QLog.Error(TAG, ex.Message, ex);
         throw;
     }
 }
コード例 #12
0
 internal void RegisterHandlerSafe(short msgType, QNetworkMessageDelegate handler)
 {
     if (handler == null)
     {
         QLog.Error($"RegisterHandlerSafe id:{msgType} handler is null");
     }
     else
     {
         QLog.Debug($"RegisterHandlerSafe id:{msgType} handler:{handler.GetMethodName()}");
         if (!_msgHandlers.ContainsKey(msgType))
         {
             _msgHandlers.Add(msgType, handler);
         }
     }
 }
コード例 #13
0
 protected void SendCommandInternal(QNetworkWriter writer, int channelId, string cmdName)
 {
     if (!IsLocalPlayer && !HasAuthority)
     {
         QLog.Warning("Trying to send command for object without authority.");
     }
     else if (QClientScene.readyConnection == null)
     {
         QLog.Error($"Send command attempted with no client running [client={ConnectionToServer}].");
     }
     else
     {
         writer.FinishMessage();
         QClientScene.readyConnection.SendWriter(writer, channelId);
     }
 }
コード例 #14
0
 public virtual void ServerChangeScene(string newSceneName)
 {
     if (string.IsNullOrEmpty(newSceneName))
     {
         QLog.Error("ServerChangeScene empty scene name");
     }
     else
     {
         QLog.Log($"ServerChangeScene {newSceneName}");
         QNetworkServer.SetAllClientsNotReady();
         networkSceneName    = newSceneName;
         s_LoadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName);
         var msg = new QStringMessage(networkSceneName);
         QNetworkServer.SendToAll(39, msg);
     }
 }
コード例 #15
0
        public static void AsyncRequestCallback(IAsyncResult ar)
        {
            RequestState requestState  = ar.AsyncState as RequestState;
            Stream       requestStream = null;

            try
            {
                HttpWebRequest httpWebRequest = requestState.httpWebRequest;

                requestStream = httpWebRequest.EndGetRequestStream(ar);

                ////开始写入数据
                //requestState.request.Body.OnWrite(requestStream);

                ////wait for response
                //httpWebRequest.BeginGetResponse(AsyncResponseCallback, requestState);

                requestState.request.Body.StartHandleRequestBody(requestStream, delegate(Exception exception)
                {
                    if (exception != null)
                    {
                        // handle request body throw exception
                        requestState.response.OnFinish(false, exception);
                        //abort
                        requestState.Clear();
                        QLog.Error(TAG, exception.Message, exception);
                    }
                    else
                    {
                        //wait for response
                        httpWebRequest.BeginGetResponse(new AsyncCallback(AsyncResponseCallback), requestState);
                    }
                });
            }
            catch (Exception ex)
            {
                requestState.response.OnFinish(false, ex);
                //abort
                requestState.Clear();
                QLog.Error(TAG, ex.Message, ex);
            }
        }
コード例 #16
0
 public void RegisterHandler(short msgType, QNetworkMessageDelegate handler)
 {
     if (handler == null)
     {
         QLog.Error($"RegisterHandler id:{msgType} handler is null");
     }
     else if (msgType <= 31)
     {
         QLog.Error($"RegisterHandler: Cannot replace system message handler {msgType}");
     }
     else
     {
         if (_msgHandlers.ContainsKey(msgType))
         {
             QLog.Log($"RegisterHandler replacing {msgType}");
             _msgHandlers.Remove(msgType);
         }
         QLog.Debug($"RegisterHandler id:{msgType} handler:{handler.GetMethodName()}");
         _msgHandlers.Add(msgType, handler);
     }
 }
コード例 #17
0
        private bool CheckChannel(int channelId)
        {
            bool result;

            if (m_Channels == null)
            {
                QLog.Warning($"Channels not initialized sending on id '{channelId}");
                result = false;
            }
            else if (channelId < 0 || channelId >= m_Channels.Length)
            {
                QLog.Error(
                    $"Invalid channel when sending buffered data, '{channelId}'. Current channel count is {m_Channels.Length}");
                result = false;
            }
            else
            {
                result = true;
            }
            return(result);
        }
コード例 #18
0
 internal void ClientChangeScene(string newSceneName, bool forceReload)
 {
     if (string.IsNullOrEmpty(newSceneName))
     {
         QLog.Error("ClientChangeScene empty scene name");
     }
     else
     {
         QLog.Log($"ClientChangeScene newSceneName:{newSceneName} networkSceneName:{networkSceneName}");
         if (newSceneName == networkSceneName)
         {
             if (!forceReload)
             {
                 FinishLoadScene();
                 return;
             }
         }
         s_LoadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName);
         networkSceneName    = newSceneName;
     }
 }
コード例 #19
0
        public override string GetMD5()
        {
            try
            {
                fileStream = new FileStream(srcPath, FileMode.Open, FileAccess.Read);
                fileStream.Seek(fileOffset, SeekOrigin.Begin);

                return(DigestUtils.GetMd5ToBase64(fileStream, contentLength));
            }
            catch (Exception ex)
            {
                QLog.Error(TAG, ex.Message, ex);
                throw;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }
コード例 #20
0
        /// <summary>
        /// handle cos response
        /// </summary>
        /// <param name="inputStream"></param>
        /// <exception cref="CosServerException"> throw CosServerException </exception>
        /// <exception cref="Exception">throw Exception</exception>
        public void HandleResponseBody(Stream inputStream)
        {
            try
            {
                if (isDownload)
                {
                    fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
                    fileStream.Seek(fileOffset, SeekOrigin.Begin);
                    byte[] buffer  = new byte[SEGMENT_SIZE];
                    int    recvLen = 0;

                    long completed = recvLen;

                    while ((recvLen = inputStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        fileStream.Write(buffer, 0, recvLen);

                        if (progressCallback != null)
                        {
                            completed += recvLen;
                            progressCallback(completed, contentLength);
                        }
                    }

                    fileStream.Flush();
                }
                else
                {
                    if ("application/xml".Equals(contentType, StringComparison.OrdinalIgnoreCase) &&
                        contentLength > 0 && contentLength < 10 * 1000)
                    {
                        // save raw content
                        memoryStream = new MemoryStream((int)contentLength);
                        inputStream.CopyTo(memoryStream);
                        rawContentBodyString = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());

                        memoryStream.Seek(0, SeekOrigin.Begin);
                        inputStream = memoryStream;
                    }

                    if (parseStream != null)
                    {
                        parseStream(inputStream, contentType, contentLength);
                    }
                }
            }
            catch (Exception ex)
            {
                QLog.Error("ResponseBody", ex.Message, ex);
                throw;
            }

            finally
            {
                if (inputStream != null)
                {
                    inputStream.Close();
                    inputStream.Dispose();
                }

                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
                //if (memoryStream != null) memoryStream.Close();
            }
        }
コード例 #21
0
        private void AsyncStreamCallback(IAsyncResult ar)
        {
            ResponseBodyState responseBodyState = ar.AsyncState as ResponseBodyState;

            Stream inputStream = responseBodyState.inputStream;

            try
            {
                int recvLen = inputStream.EndRead(ar);

                responseBodyState.completed += recvLen;

                if (recvLen > 0)
                {
                    if (isDownload)
                    {
                        fileStream.Write(responseBodyState.buffer, 0, recvLen);

                        if (progressCallback != null)
                        {
                            progressCallback(responseBodyState.completed, contentLength);
                        }
                    }
                    else
                    {
                        memoryStream.Write(responseBodyState.buffer, 0, recvLen);
                    }

                    inputStream.BeginRead(responseBodyState.buffer, 0, responseBodyState.buffer.Length, AsyncStreamCallback, responseBodyState);
                }
                else
                if (recvLen == 0)
                {
                    if (isDownload)
                    {
                        fileStream.Flush();
                    }
                    else
                    {
                        if ("application/xml".Equals(contentType, StringComparison.OrdinalIgnoreCase) &&
                            memoryStream.Length > 0 && memoryStream.Length < 10 * 1000)
                        {
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            rawContentBodyString = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
                        }

                        memoryStream.Seek(0, SeekOrigin.Begin);
                        parseStream(memoryStream, contentType, responseBodyState.completed);
                    }

                    responseBodyState.endResponseBody(true, null);
                    responseBodyState.Clear();

                    if (fileStream != null)
                    {
                        fileStream.Close();
                        fileStream.Dispose();
                    }

                    if (memoryStream != null)
                    {
                        memoryStream.Close();
                        memoryStream.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                responseBodyState.endResponseBody(false, ex);
                responseBodyState.Clear();

                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }

                if (memoryStream != null)
                {
                    memoryStream.Close();
                    memoryStream.Dispose();
                }

                QLog.Error("ResponseBody", ex.Message, ex);
            }
        }
コード例 #22
0
        public static void AsyncResponseCallback(IAsyncResult ar)
        {
            RequestState    requestState    = ar.AsyncState as RequestState;
            HttpWebResponse httpWebResponse = null;

            try
            {
                HttpWebRequest httpWebRequest = requestState.httpWebRequest;

                httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(ar);

                //nofity get response
                requestState.request.onNotifyGetResponse();

                requestState.httpWebResponse = httpWebResponse;
                //handle response headers
                HandleHttpWebResponseHeaders(requestState.response, httpWebResponse);

                Stream responseStream = httpWebResponse.GetResponseStream();


                requestState.response.Body.StartHandleResponseBody(responseStream, delegate(bool isSuccess, Exception ex)
                {
                    PrintResponseInfo(httpWebResponse);
                    requestState.response.OnFinish(isSuccess, ex);
                    requestState.Clear();
                });
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null && webEx.Response is HttpWebResponse)
                {
                    //nofity get response
                    requestState.request.onNotifyGetResponse();

                    //handle response for [400, 500]
                    httpWebResponse = (HttpWebResponse)webEx.Response;

                    requestState.httpWebResponse = httpWebResponse;

                    //handle response headers
                    HandleHttpWebResponseHeaders(requestState.response, httpWebResponse);

                    Stream responseStream = httpWebResponse.GetResponseStream();


                    requestState.response.Body.StartHandleResponseBody(responseStream, delegate(bool isSuccess, Exception ex)
                    {
                        PrintResponseInfo(httpWebResponse);
                        requestState.response.OnFinish(isSuccess, ex);
                        requestState.Clear();
                    });
                }
                else
                {
                    requestState.response.OnFinish(false, webEx);
                    //abort
                    requestState.Clear();
                    QLog.Error(TAG, webEx.Message, webEx);
                }
            }
            catch (Exception ex)
            {
                requestState.response.OnFinish(false, ex);
                //abort
                requestState.Clear();
                QLog.Error(TAG, ex.Message, ex);
            }
        }