/// <summary> /// Applies operation /// </summary> protected override void DoOperation() { var un = Command.Parameters["un"] as ParameterString; var st = Command.Parameters["st"] as ParameterBoolean; for (int i = 0; i < Server.Clients.Count; i++) { if (Server.Clients[i].Username == un.Value) { var command = new NetCommand(CommandNames.INFORM_WRITING_STATE); command.Parameters.Add(new ParameterString("un", Client.Username)); command.Parameters.Add(st); Server.Clients[i].Commands.Add(command); Response = new NetResponse(true); return; } } Response = new NetResponse(false, "User could not found"); }
private void DoLoginOperation(object sender, EventArgs e) { NetResponse response = sender as NetResponse; if (response.Okey) { lvwUsers.Items.Clear(); lvwUsers.Visible = true; pnlLoginScreen.Visible = false; signOutToolStripMenuItem.Enabled = true; durumToolStripMenuItem.Enabled = true; base.Text = "B-MSN by Ozcan DEGIRMENCI - " + txtUsername.Text; } else { MessageBox.Show(response.Message); pnlLoginScreen.Enabled = true; base.Text = "B-MSN by Ozcan DEGIRMENCI"; } }
void OnDetailHandler(NetResponse response) { if (response.Succeeded) { MailDetailResponse mdResponse = (MailDetailResponse)response; MailVo mv = listContainer.GetItemByMailId(mdResponse.MailId).MailVo; mv.Content = mdResponse.Content; mv.Attachments = mdResponse.Attachments; mv.ReceiveTime = mdResponse.ReceiveTime; mv.HasRead = true; mv.IsComplete = true; if (detailContainer.MailVo.MailId == mdResponse.MailId) { detailContainer.MailVo = mv; } } else { UIMessageBoxManager.Instance.ShowErrorMessageBox(response.errorCode, "Mail"); } }
public static void DebugCommandResponse(NetResponse response, ref BinaryReader reader) { return; string commandName = response.GetType().Name; Regex regex = new Regex("Response"); commandName = regex.Split(commandName)[0]; FileInfo info = new FileInfo(Application.streamingAssetsPath + "/command/" + commandName + ".txt"); if (info.Exists) { info.Delete(); } FileStream fs = info.Create(); fs.Position = 0; fs.SetLength(0); MemoryStream s = new MemoryStream(); int BUFFER_SIZE = 1024; byte[] buf = new byte[BUFFER_SIZE]; int n = reader.Read(buf, 0, BUFFER_SIZE); while (n > 0) { s.Write(buf, 0, n); fs.Write(buf, 0, n); n = reader.Read(buf, 0, BUFFER_SIZE); } s.Position = 0; reader = new BinaryReader(s); fs.Close(); fs.Dispose(); }
/// <summary> /// Aplies operation /// </summary> protected override void DoOperation() { var un = Command.Parameters["un"] as ParameterString; var msg = Command.Parameters["msg"] as ParameterString; for (int i = 0; i < Server.Clients.Count; i++) { if (Server.Clients[i].Username == un.Value) { var command = new NetCommand(CommandNames.SEND_MESSAGE); command.Parameters.Add(un); command.Parameters.Add(new ParameterString("fr", Client.Username)); command.Parameters.Add(msg); Server.Clients[i].Commands.Add(command); Response = new NetResponse(true); return; } } Response = new NetResponse(false, "User could not found"); }
/// <summary> /// Starts the command operation /// </summary> public void StartOperation() { Status = CommandOperationStatus.OnOperation; try { if (CheckSecurity()) { DoOperation(); } else { Response = NetResponse.NotAllowed(); } } catch (Exception ex) { Response = NetResponse.SystemError(ex.Message); } finally { Status = CommandOperationStatus.Finished; } }
void OnBindCallBack(NetResponse msg) { ConnectionManager.Instance.SendACK(OnRequestBind, true); if (msg.errorCode == 0) { PlayerPrefs.SetString(PrefsKey.Account, accountContent.text); PlayerPrefs.SetString(PrefsKey.Password, passwordContent.text); NetworkManager.Instance.Account = accountContent.text; NetworkManager.Instance.Password = passwordContent.text; NetworkManager.Instance.IsAccountBind = true; //CharacterSelector.Instance.IsLoadingCharacter = true; CharacterSelector.Instance.RefreshAccount(); successMessageBox = UIMessageBoxManager.Instance.ShowMessageBox(Localization.Localize("IDS_MESSAGE_LOGIN_BOUNDSUCCESSFUL"), "", MB_TYPE.MB_OK, OnCloseSuccessTips); } else { string errorMessage = Utils.GetErrorIDS(msg.errorCode); UIMessageBoxManager.Instance.ShowMessageBox(errorMessage, "", MB_TYPE.MB_OK, null); } }
public override void Parse(System.IO.BinaryReader reader) { _item_GUID = reader.ReadInt64(); _itemID = NetResponse.ReadString(reader); _count = reader.ReadInt16(); byte itemPropNum = reader.ReadByte(); for (int i = 0; i < itemPropNum; i++) { FC_EQUIP_EXTEND_ATTRIBUTE attKey = (FC_EQUIP_EXTEND_ATTRIBUTE)reader.ReadInt32(); int attValue = reader.ReadInt32(); if (_extendAttributes.ContainsKey(attKey)) { _extendAttributes[attKey] = attValue; } else { _extendAttributes.Add(attKey, attValue); } } }
void OnQureyHCPriceHandler(NetResponse response) { _priceGot = true; if (response.Succeeded) { StoreHCPriceQueryResponse sResponse = (StoreHCPriceQueryResponse)response; int totalCost = 0; foreach (InventoryHCWorth hcWorth in WantBuyItems) { hcWorth.OnePrice = sResponse.InventoryHCWorthMapping[hcWorth.ItemId].OnePrice; hcWorth.Discount = sResponse.InventoryHCWorthMapping[hcWorth.ItemId].Discount; hcWorth.DiscountPrice = sResponse.InventoryHCWorthMapping[hcWorth.ItemId].DiscountPrice; totalCost += hcWorth.Count * hcWorth.DiscountPrice; MakeSupplementItem(hcWorth); } grid.repositionNow = true; buyDescribeLabel.text = string.Format(Localization.Localize("IDS_MESSAGE_FUSION_HCCOSTCONDIRM"), totalCost); } else { UIMessageBoxManager.Instance.ShowErrorMessageBox(response.errorCode, "UIFusion"); } }
public void SendCommand(NetRequest request, ServerCallbackDelegate callback) { if (!isOfflinePlay) { Debug.Log("[SEND MSG]" + request.GetType().Name + "=>"); _client.SendCommand(request, delegate(NetResponse msg) { callback(msg); Debug.Log("[RECIVE MSG]" + request.GetType().Name + "<=" + msg.ToString()); }); return; } Regex regex = new Regex("Request"); string cmdname = regex.Split(request.GetType().Name)[0]; FileInfo info = new FileInfo(Application.streamingAssetsPath + "/command/" + cmdname + ".txt"); if (!info.Exists) { Debug.Log("[NOT RUN MSG]" + cmdname + ""); return; } NetResponse response = Activator.CreateInstance( Assembly.GetAssembly(request.GetType()) .GetType(cmdname + "Response") ) as FaustComm.NetResponse; FileStream fs = info.OpenRead(); fs.Position = 0; BinaryReader br = new BinaryReader(fs); response.Decode(br); callback(response); fs.Close(); fs.Dispose(); Debug.Log("[RUN MSG]" + cmdname + ""); }
private void OnLoginCallback(NetResponse msg) { if (msg.errorCode == 0) { LoginResponse myMsg = (LoginResponse)msg; _client.accountID = myMsg.accountId; _client.sessionID = myMsg.session; Debug.Log(string.Format("Login succeeded. AccountId = {0} Session id = {1}", myMsg.accountId, myMsg.session)); LoadCharacterSelectionScene(); } else { Debug.Log("Login failed. Error code = " + msg.errorCode); switch (msg.errorCode) { case 1001: _account = NetworkUtils.GetUDID(); PlayerPrefs.SetString(PrefsKey.Account, _account); _password = NetworkUtils.GetUDPassword(_account); PlayerPrefs.SetString(PrefsKey.Password, _password); NetworkManager.Instance.RegisterNewUser(_account, _password, string.Empty, OnRegister); break; case 1005: Debug.LogError(" Account of illegal "); break; } } }
void OnOperateOneMail(NetResponse response) { if (response.Succeeded) { MailOperationResponse moResponse = (MailOperationResponse)response; moResponse.UpdateData.Broadcast(); if (moResponse.Operation == MailOperation.RemoveOne) { if (null != OnRemoveMailHandler) { OnRemoveMailHandler(moResponse.MailId); } } else if (moResponse.Operation == MailOperation.CollectOne) { _mailVo.Collectable = false; Refresh(); } } else { UIMessageBoxManager.Instance.ShowErrorMessageBox(response.errorCode, "Mail"); } }
String requestClientIDByNet() { //String strBody = ""; //TODO: send client register info in client create // if ( ClientRegister.getInstance() != null ) // strBody += ClientRegister.getInstance().getRegisterBody(); NetResponse resp = getNetClientID().pullData(getProtocol().getClientCreateUrl(), this); if (resp.isOK() && resp.getCharData() != null) { String szData = resp.getCharData(); JSONEntry oJsonEntry = new JSONEntry(szData); //if (oJsonEntry.hasName("sources") ) // processServerSources(szData); JSONEntry oJsonObject = oJsonEntry.getEntry("client"); if (!oJsonObject.isEmpty()) { return(oJsonObject.getString("client_id")); } } else { m_nErrCode = RhoAppAdapter.getErrorFromResponse(resp); if (m_nErrCode == RhoAppAdapter.ERR_NONE) { m_nErrCode = RhoAppAdapter.ERR_UNEXPECTEDSERVERRESPONSE; m_strError = resp.getCharData(); } } return(""); }
public void doSearch(Vector <String> arSources, String strParams, String strAction, boolean bSearchSyncChanges, int nProgressStep) { try { prepareSync(esSearch, null); if (!isContinueSync()) { if (getState() != esExit) { setState(esNone); } return; } TimeInterval startTime = TimeInterval.getCurrentTime(); if (bSearchSyncChanges) { for (int i = 0; i < (int)arSources.size(); i++) { SyncSource pSrc = findSourceByName((String)arSources.elementAt(i)); if (pSrc != null) { pSrc.syncClientChanges(); } } } while (isContinueSync()) { int nSearchCount = 0; String strUrl = getProtocol().getServerQueryUrl(strAction); String strQuery = getProtocol().getServerQueryBody("", getClientID(), getSyncPageSize()); if (strParams.length() > 0) { strQuery += strParams; } String strTestResp = ""; for (int i = 0; i < (int)arSources.size(); i++) { SyncSource pSrc = findSourceByName((String)arSources.elementAt(i)); if (pSrc != null) { strQuery += "&sources[][name]=" + pSrc.getName(); if (!pSrc.isTokenFromDB() && pSrc.getToken() > 1) { strQuery += "&sources[][token]=" + pSrc.getToken(); } strTestResp = getSourceOptions().getProperty(pSrc.getID(), "rho_server_response"); } } LOG.INFO("Call search on server. Url: " + (strUrl + strQuery)); NetResponse resp = getNet().pullData(strUrl + strQuery, this); if (!resp.isOK()) { stopSync(); m_nErrCode = RhoAppAdapter.getErrorFromResponse(resp); m_strError = resp.getCharData(); continue; } String szData = null; if (strTestResp != null && strTestResp.length() > 0) { szData = strTestResp; } else { szData = resp.getCharData(); } JSONArrayIterator oJsonArr = new JSONArrayIterator(szData); for ( ; !oJsonArr.isEnd() && isContinueSync(); oJsonArr.next()) { JSONArrayIterator oSrcArr = oJsonArr.getCurArrayIter(); //new JSONArrayIterator(oJsonArr.getCurItem()); if (oSrcArr.isEnd()) { break; } int nVersion = 0; if (!oSrcArr.isEnd() && oSrcArr.getCurItem().hasName("version")) { nVersion = oSrcArr.getCurItem().getInt("version"); oSrcArr.next(); } if (nVersion != getProtocol().getVersion()) { LOG.ERROR("Sync server send search data with incompatible version. Client version: " + getProtocol().getVersion() + "; Server response version: " + nVersion); stopSync(); m_nErrCode = RhoAppAdapter.ERR_SYNCVERSION; continue; } if (!oSrcArr.isEnd() && oSrcArr.getCurItem().hasName("token")) { oSrcArr.next(); } if (!oSrcArr.getCurItem().hasName("source")) { LOG.ERROR("Sync server send search data without source name."); stopSync(); m_nErrCode = RhoAppAdapter.ERR_UNEXPECTEDSERVERRESPONSE; m_strError = szData; continue; } String strSrcName = oSrcArr.getCurItem().getString("source"); SyncSource pSrc = findSourceByName(strSrcName); if (pSrc == null) { LOG.ERROR("Sync server send search data for unknown source name:" + strSrcName); stopSync(); m_nErrCode = RhoAppAdapter.ERR_UNEXPECTEDSERVERRESPONSE; m_strError = szData; continue; } oSrcArr.reset(0); pSrc.setProgressStep(nProgressStep); pSrc.processServerResponse_ver3(oSrcArr); nSearchCount += pSrc.getCurPageCount(); if (pSrc.getServerError().length() > 0) { if (m_strServerError.length() > 0) { m_strServerError += "&"; } m_strServerError += pSrc.getServerError(); m_nErrCode = pSrc.getErrorCode(); } } if (nSearchCount == 0) { for (int i = 0; i < (int)arSources.size(); i++) { SyncSource pSrc = findSourceByName((String)arSources.elementAt(i)); if (pSrc != null) { pSrc.processToken(0); } } break; } } getNotify().fireAllSyncNotifications(true, m_nErrCode, m_strError, m_strServerError); //update db info TimeInterval endTime = TimeInterval.getCurrentTime(); //unsigned long timeUpdated = CLocalTime().toULong(); for (int i = 0; i < (int)arSources.size(); i++) { SyncSource oSrc = findSourceByName((String)arSources.elementAt(i)); if (oSrc == null) { continue; } oSrc.getDB().executeSQL("UPDATE sources set last_updated=?,last_inserted_size=?,last_deleted_size=?, " + "last_sync_duration=?,last_sync_success=?, backend_refresh_time=? WHERE source_id=?", endTime.toULong() / 1000, oSrc.getInsertedCount(), oSrc.getDeletedCount(), endTime.minus(startTime).toULong(), oSrc.getGetAtLeastOnePage()?1:0, oSrc.getRefreshTime(), oSrc.getID()); } // getNotify().cleanCreateObjectErrors(); if (getState() != esExit) { setState(esNone); } } catch (Exception exc) { LOG.ERROR("Search failed.", exc); getNotify().fireAllSyncNotifications(true, RhoAppAdapter.ERR_RUNTIME, "", ""); } }
public void login(String name, String password, SyncNotify.SyncNotification oNotify) { try { /* * processServerSources("{\"sources\":{ \"ProductEx\":{ "+ * "\"sync_type\":\"incremental\", \"partition\":\"application\", \"source_id\":\"7\","+ * " \"sync_priority\":\"0\", \"model_type\":\"fixed_schema\", "+ * " \"schema\":{\"version\":\"1.1\", \"property\":{\"brand\":\"string\", \"price\":\"string\", \"quantity\":\"string\", \"name\":\"string\", "+ * " \"image_url\":\"blob\", \"image_url_ex\":\"blob,overwrite\"}, "+ * " \"index\":[{\"by_brand_price1\":\"brand,price\"}, {\"by_quantity1\":\"quantity\"}], \"unique_index\":[{\"by_name1\":\"name\"}]}, "+ * " \"belongs_to\":{\"brand\":\"Customer\"}}}}");//, \"schema_version\":\"1.0\" */ NetResponse resp = null; m_bStopByUser = false; try{ resp = getNet().pullCookies(getProtocol().getLoginUrl(), getProtocol().getLoginBody(name, password), this); int nErrCode = RhoAppAdapter.getErrorFromResponse(resp); if (nErrCode != RhoAppAdapter.ERR_NONE) { getNotify().callLoginCallback(oNotify, nErrCode, resp.getCharData()); return; } }catch (Exception exc) { LOG.ERROR("Login failed.", exc); getNotify().callLoginCallback(oNotify, RhoAppAdapter.getNetErrorCode(exc), ""); return; } String strSession = resp.getCharData(); if (strSession == null || strSession.length() == 0) { LOG.ERROR("Return empty session."); getNotify().callLoginCallback(oNotify, RhoAppAdapter.ERR_UNEXPECTEDSERVERRESPONSE, ""); return; } if (isStoppedByUser()) { return; } IDBResult res = getUserDB().executeSQL("SELECT * FROM client_info"); if (!res.isEnd()) { getUserDB().executeSQL("UPDATE client_info SET session=?", strSession); } else { getUserDB().executeSQL("INSERT INTO client_info (session) values (?)", strSession); } if (RHOCONF().isExist("rho_sync_user")) { String strOldUser = RHOCONF().getString("rho_sync_user"); if (name.compareTo(strOldUser) != 0) { if (isNoThreadedMode()) { RhoRuby.resetDBOnSyncUserChanged(); } else { NetResponse resp1 = getNet().pushData(getNet().resolveUrl("/system/resetDBOnSyncUserChanged"), "", null); } } } RHOCONF().setString("rho_sync_user", name, true); getNotify().callLoginCallback(oNotify, RhoAppAdapter.ERR_NONE, ""); if (ClientRegister.getInstance() != null) { getUserDB().executeSQL("UPDATE client_info SET token_sent=?", 0); ClientRegister.getInstance().startUp(); } }catch (Exception exc) { LOG.ERROR("Login failed.", exc); getNotify().callLoginCallback(oNotify, RhoAppAdapter.ERR_RUNTIME, ""); } }
private void FatalServerErrorCallback(NetResponse msg) { UIMessageBoxManager.Instance.ShowMessageBox(Utils.GetErrorIDS(msg.errorCode), null, MB_TYPE.MB_OK, OnFatalError); }
/// <summary> /// Process client operations /// </summary> private void ClientProcess() { DateTime lastCommandDate = DateTime.Now; _SocketReader.Socket = Socket; _SocketReader.SleepTime = 5; // 5 ms _SocketReader.Timeout = Server.CommandTimeout; _BadCommandCount = 0; try { // send welcome message to the client var response = new NetResponse(true, "Server is ready at " + DateTime.Now.ToString("yyyyMMdd HH:mm:ss")); response.CommandId = -1; response.Parameters.Add(new ParameterInt32("hash", Guid.GetHashCode())); Send(response); Server.OnClientConnected(this); double time = 0; response = null; bool badcommand = false; NetCommand command = null; while (_IsOnProcess) { response = null; badcommand = false; command = null; if (Socket.Available > 0) { _SocketReader.Clear(); _SocketReader.Read(); lastCommandDate = DateTime.Now; if (_SocketReader.LastStatus == SocketReader.ReadStatus.Success) { try { if (_SocketReader.Type == SocketReader.ReadType.Command) { command = NetCommand.Parse(_SocketReader.Data); command.Id = _SocketReader.CommandId; CommandOperationEventArgs e = new CommandOperationEventArgs(command); OnNewCommand(e); if (!e.Handled) { badcommand = true; } } else { command = _SendedCommands[_SocketReader.CommandId] as NetCommand; if (command != null) { response = NetResponse.Parse(_SocketReader.Data); response.CommandId = _SocketReader.CommandId; command.Response = response; command.Status = CommandStatus.Executed; _SendedCommands.Remove(command.Id); } } } catch (Exception exception) { Server.OnSystemError(exception); badcommand = true; } if (badcommand) { _BadCommandCount++; if (_SocketReader.Type == SocketReader.ReadType.Command) { if (command != null) { response = new NetResponse(false, "Bad command"); command.Response = response; Send(response); command.Status = CommandStatus.Executed; } } else { command = _SendedCommands[response.CommandId] as NetCommand; if (command != null) { command.Response = new NetResponse(false, "Bad command"); command.Status = CommandStatus.Executed; _SendedCommands.Remove(command.Id); } } if (_BadCommandCount > Server.BadCommandCount) { response = new NetResponse(false, "Because of too much bad commands your connection will be terminated"); Send(response); break; } } } else { switch (_SocketReader.LastStatus) { case SocketReader.ReadStatus.Exception: response = new NetResponse(false, "Socket reading exception"); Send(response); break; case SocketReader.ReadStatus.Timeout: response = new NetResponse(false, "Timeout"); Send(response); break; default: response = new NetResponse(false, "Unknow socket reading exception"); Send(response); break; } } } else { NetCommand active = null; for (int k = 0; k < Commands.Count; k++) { NetCommand cd = Commands[k, true]; if (cd.Status == CommandStatus.Waiting) { active = cd; break; } } if (active != null) { active.Status = CommandStatus.SendingToTarget; Send(active); _SendedCommands.Add(active.Id, active); active.Status = CommandStatus.WaitingForResponse; } else { time = DateTime.Now.Subtract(lastCommandDate).TotalMilliseconds; if (time > Server.ConnectionTimeout) { response = new NetResponse(false, "Connection is timeout"); Send(response); Disconnect(); break; } Thread.Sleep(10); } } } } catch (SocketException ex) { if (ex.NativeErrorCode == 0x2745) { // connection close by remote host is not an exception (client might be closed) } else if (ex.NativeErrorCode != 0x2714) // WSACancelBlockCall (We might close) { Server.OnSystemError(new Exception(string.Format("Socket exception in Client {0}", Guid.ToString("N")), ex)); } } catch (Exception ex) { Server.OnSystemError(new Exception(string.Format("Exception in Client {0}", Guid.ToString("N")), ex)); } finally{ Disconnect(); } }
/// <summary> /// Applies operation /// </summary> protected override void DoOperation() { Response = new NetResponse(true, string.Empty); }
/// <summary> /// Applies operation /// </summary> protected override void DoOperation() { Response = new NetResponse(true, "Hi hash: " + Client.HashCode.ToString()); }
public NetResponse Execute() { NetResponse NR = new NetResponse(); try { NR.HasError = false; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(_json); // Send the data to Salesforce var request = (HttpWebRequest)(HttpWebRequest.Create(_url)); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; request.ContentLength = bytes.Length; // Attach the access token and JSON to the request to Salesforce. request.Headers.Add("Authorization: OAuth " + Connector.Instance.GetSecurityToken()); using (var requestWriter = new StreamWriter(request.GetRequestStream())) { requestWriter.Write(_json); requestWriter.Flush(); requestWriter.Close(); } // Send the object to Salesforce var response = request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { var data = reader.ReadToEnd(); OAuthResponse oRes = new OAuthResponse(data); NR.JSON = data; NR.OAuthResponse = oRes; } } catch (WebException wex) { NR.HasError = true; if (wex.Response != null) { using (var errorResponse = (HttpWebResponse)wex.Response) { using (var reader = new StreamReader(errorResponse.GetResponseStream())) { string error = reader.ReadToEnd(); NR.ErrorMessage = error; MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(error)); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List <ErrorResponse>)); List <ErrorResponse> errResponses = (List <ErrorResponse>)ser.ReadObject(ms); if (errResponses != null) { NR.ErrorResponses = errResponses; } } } } } catch (Exception ex) { NR.HasError = true; NR.ErrorMessage = ex.Message; } return(NR); }
void doSyncClientChanges() { String[] arUpdateTypes = { "create", "update", "delete" }; boolean[] arUpdateSent = { false, false, false }; m_arMultipartItems.removeAllElements(); m_arBlobAttrs.removeAllElements(); String strBody = "{\"source_name\":" + JSONEntry.quoteValue(getName()) + ",\"client_id\":" + JSONEntry.quoteValue(getSync().getClientID()); boolean bSend = false; int i = 0; for (i = 0; i < 3 && getSync().isContinueSync(); i++) { String strBody1; strBody1 = makePushBody_Ver3(arUpdateTypes[i], true); if (strBody1.length() > 0) { strBody += "," + strBody1; String strBlobAttrs = ""; for (int j = 0; j < (int)m_arBlobAttrs.size(); j++) { if (strBlobAttrs.length() > 0) { strBlobAttrs += ","; } strBlobAttrs += JSONEntry.quoteValue((String)m_arBlobAttrs.elementAt(j)); } if (strBlobAttrs.length() > 0) { strBody += ",\"blob_fields\":[" + strBlobAttrs + "]"; } arUpdateSent[i] = true; bSend = true; } } strBody += "}"; if (bSend) { LOG.INFO("Push client changes to server. Source: " + getName() + "Size :" + strBody.length()); LOG.TRACE("Push body: " + strBody); try{ if (m_arMultipartItems.size() > 0) { NetRequest.MultipartItem oItem = new NetRequest.MultipartItem(); oItem.m_strBody = strBody; //oItem.m_strContentType = getProtocol().getContentType(); oItem.m_strName = "cud"; m_arMultipartItems.addElement(oItem); NetResponse resp = getNet().pushMultipartData(getProtocol().getClientChangesUrl(), m_arMultipartItems, getSync(), null); if (!resp.isOK()) { getSync().setState(SyncEngine.esStop); m_nErrCode = RhoAppAdapter.ERR_REMOTESERVER; m_strError = resp.getCharData(); } } else { NetResponse resp = getNet().pushData(getProtocol().getClientChangesUrl(), strBody, getSync()); if (!resp.isOK()) { getSync().setState(SyncEngine.esStop); m_nErrCode = RhoAppAdapter.ERR_REMOTESERVER; m_strError = resp.getCharData(); } } }catch (Exception exc) { m_nErrCode = RhoAppAdapter.getNetErrorCode(exc); throw exc; } } for (i = 0; i < 3 && getSync().isContinueSync(); i++) { if (arUpdateSent[i]) { //oo conflicts if (i < 1) //create { getDB().executeSQL("UPDATE changed_values SET sent=2 WHERE source_id=? and update_type=? and sent=1", getID(), arUpdateTypes[i]); } else { // getDB().executeSQL("DELETE FROM changed_values WHERE source_id=? and update_type=? and sent=1", getID(), arUpdateTypes[i]); } } } m_arMultipartItems.removeAllElements(); m_arBlobAttrs.removeAllElements(); }
void loadBulkPartition(String strPartition) { DBAdapter dbPartition = getDB(strPartition); String serverUrl = RhoConf.getInstance().getPath("syncserver"); String strUrl = serverUrl + "bulk_data"; String strQuery = "?client_id=" + m_clientID + "&partition=" + strPartition; String strDataUrl = "", strCmd = "", strCryptKey = ""; getNotify().fireBulkSyncNotification(false, "start", strPartition, RhoAppAdapter.ERR_NONE); while (strCmd.length() == 0 && isContinueSync()) { NetResponse resp = getNet().pullData(strUrl + strQuery, this); if (!resp.isOK() || resp.getCharData() == null) { LOG.ERROR("Bulk sync failed: server return an error."); stopSync(); getNotify().fireBulkSyncNotification(true, "", strPartition, RhoAppAdapter.getErrorFromResponse(resp)); return; } LOG.INFO("Bulk sync: got response from server: " + resp.getCharData()); String szData = resp.getCharData(); JSONEntry oJsonEntry = new JSONEntry(szData); strCmd = oJsonEntry.getString("result"); if (oJsonEntry.hasName("url")) { strDataUrl = oJsonEntry.getString("url"); } if (strCmd.compareTo("wait") == 0) { int nTimeout = RhoConf.getInstance().getInt("bulksync_timeout_sec"); if (nTimeout == 0) { nTimeout = 5; } SyncThread.getInstance().wait(nTimeout); strCmd = ""; } } if (strCmd.compareTo("nop") == 0) { LOG.INFO("Bulk sync return no data."); getNotify().fireBulkSyncNotification(true, "", strPartition, RhoAppAdapter.ERR_NONE); return; } if (!isContinueSync()) { return; } getNotify().fireBulkSyncNotification(false, "download", strPartition, RhoAppAdapter.ERR_NONE); String fDataName = makeBulkDataFileName(strDataUrl, dbPartition.getDBPath(), ""); String strZip = ".rzip"; String strSqlDataUrl = CFilePath.join(getHostFromUrl(serverUrl), strDataUrl) + strZip; LOG.INFO("Bulk sync: download data from server: " + strSqlDataUrl); { NetResponse resp1 = getNet().pullFile(strSqlDataUrl, fDataName + strZip, this, null); if (!resp1.isOK()) { LOG.ERROR("Bulk sync failed: cannot download database file."); stopSync(); getNotify().fireBulkSyncNotification(true, "", strPartition, RhoAppAdapter.getErrorFromResponse(resp1)); return; } } if (!isContinueSync()) { return; } LOG.INFO("Bulk sync: unzip db"); if (!RHODESAPP().unzip_file(fDataName + strZip)) { CRhoFile.deleteFile(fDataName + strZip); LOG.ERROR("Bulk sync failed: cannot unzip database file."); stopSync(); getNotify().fireBulkSyncNotification(true, "", strPartition, RhoAppAdapter.ERR_UNEXPECTEDSERVERRESPONSE); return; } CRhoFile.deleteFile(fDataName + strZip); LOG.INFO("Bulk sync: start change db"); getNotify().fireBulkSyncNotification(false, "change_db", strPartition, RhoAppAdapter.ERR_NONE); dbPartition.setBulkSyncDB(fDataName, strCryptKey); processServerSources("{\"partition\":\"" + strPartition + "\"}"); LOG.INFO("Bulk sync: end change db"); getNotify().fireBulkSyncNotification(false, "", strPartition, RhoAppAdapter.ERR_NONE); }
/// <summary> /// Listen and process messages /// </summary> private void ProcessOperation() { var lastCommandDate = DateTime.Now; var time = 0; _SocketReader.Clear(); _SocketReader.SleepTime = 5; _SocketReader.Socket = _Socket; _SocketReader.Timeout = CommandTimeout; NetResponse response = null; try { while (_ProcessFlag) { response = null; if (_Socket.Available > 0) { OnBeginReceiveData(); _SocketReader.Clear(); _SocketReader.Read(); OnEndReceiveData(); if (_SocketReader.LastStatus == SocketReader.ReadStatus.Success) { if (_SocketReader.Type == SocketReader.ReadType.Command) { NetCommand command = NetCommand.Parse(_SocketReader.Data); command.Id = _SocketReader.CommandId; ServerCommandsManager.PublishCommandExecute(command); command.Status = CommandStatus.Executed; if (command.Response == null) { command.Response = new NetResponse(false, "Server command could not be executed"); } Send(command.Response); } else { var command = _SendCommands[_SocketReader.CommandId] as NetCommand; if (command == null) { OnUnknownServerData(); } else { response = NetResponse.Parse(_SocketReader.Data); command.Response = response; command.Status = CommandStatus.Executed; CommandExecutionManager.PublishCommandExecute(command); _SendCommands.Remove(command.Id); } } } else { Disconnect(); } lastCommandDate = DateTime.Now; } else { NetCommand active = null; for (int k = 0; k < Commands.Count; k++) { NetCommand cd = Commands[k, true]; if (cd.Status == CommandStatus.Waiting) { active = cd; break; } } if (active != null) { Commands.Active = active; OnBeginSendingData(); Send(active); OnEndSendingData(); _SendCommands.Add(active.Id, active); } else { time = Convert.ToInt32(DateTime.Now.Subtract(lastCommandDate).TotalMilliseconds); if (KeepConnection && time >= NoopPeriod) { Commands.Add(new NetCommand(CommandNames.NOOP)); } else { if (time > ConnectionTimeout) { break; } } Thread.Sleep(10); } } } } catch (SocketException ex) { if (ex.NativeErrorCode != 0x2745 && ex.NativeErrorCode != 0x2714) { throw ex; } } catch (Exception ex) { OnSystemError(ex); } finally { Disconnect(); } }
/// <summary> /// Internal connect operation /// </summary> private void InternalConnect() { Commands.Clear(); SetSocketStatus(SocketStatus.Connecting); IPEndPoint host = new IPEndPoint(IPAddress.Parse(Server), Port); _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { _Socket.Connect(host); if (_Socket.Connected) { _SocketReader.Socket = _Socket; _SocketReader.Timeout = ConnectingTimeout; _SocketReader.SleepTime = 10; if (_SocketReader.Read() == SocketReader.ReadStatus.Success && _SocketReader.Type == SocketReader.ReadType.Response && _SocketReader.CommandId == -1) { var response = NetResponse.Parse(_SocketReader.Data); if (response.Okey) { var hash = response.Parameters["hash"] as ParameterInt32; HashCode = hash.Value; SetSocketStatus(SocketStatus.Connected); _ProcessFlag = true; ConnectTime = DateTime.Now; ProcessOperation(); } else { _Socket.Shutdown(SocketShutdown.Both); _Socket.Close(); SetSocketStatus(SocketStatus.None); } } else { _Socket.Shutdown(SocketShutdown.Both); _Socket.Close(); SetSocketStatus(SocketStatus.None); } } else { SetSocketStatus(SocketStatus.None); } } catch //(Exception exception) { if (_Socket != null && _Socket.Connected) { _Socket.Shutdown(SocketShutdown.Both); _Socket.Close(); } SetSocketStatus(SocketStatus.Error); } }
void syncServerChanges() { LOG.INFO("Sync server changes source ID :" + getID()); while (getSync().isContinueSync()) { setCurPageCount(0); String strUrl = getProtocol().getServerQueryUrl(""); String strQuery = getProtocol().getServerQueryBody(getName(), getSync().getClientID(), getSync().getSyncPageSize()); if (!m_bTokenFromDB && getToken() > 1) { strQuery += "&token=" + getToken(); } LOG.INFO("Pull changes from server. Url: " + (strUrl + strQuery)); NetResponse resp = null; try{ PROF.START("Net"); resp = getNet().pullData(strUrl + strQuery, getSync()); PROF.STOP("Net"); if (!resp.isOK()) { getSync().stopSync(); m_nErrCode = RhoAppAdapter.getErrorFromResponse(resp); m_strError = resp.getCharData(); continue; } }catch (Exception exc) { m_nErrCode = RhoAppAdapter.getNetErrorCode(exc); throw exc; } String szData = null; String strTestResp = SyncEngine.getSourceOptions().getProperty(getID(), "rho_server_response"); if (strTestResp != null && strTestResp.length() > 0) { szData = strTestResp; } else { szData = resp.getCharData(); } PROF.START("Parse"); JSONArrayIterator oJsonArr = new JSONArrayIterator(szData); PROF.STOP("Parse"); processServerResponse_ver3(oJsonArr); if (SyncEngine.getSourceOptions().getBoolProperty(getID(), "pass_through")) { processToken(0); } if (getToken() == 0) { break; } } if (getSync().isSchemaChanged()) { getSync().stopSync(); } }
/// <summary> /// 处理服务器回应数据 /// </summary> /// <param name="response"></param> public void DoRankNetResponse(NetResponse response) { rolepower = JsonConvert.DeserializeObject <List <RolePower> >(response.Data); StartCoroutine(Rank()); //开启排行榜协成 }
/// <summary> /// 解析从客户端发来的请求数据 /// </summary> /// <param name="request"></param> void ParseNetRequest(NetRequest request) { if (request.Type == "Chat")//聊天 { NetResponse response = new NetResponse(); response.Type = request.Type; response.Code = 1; response.Data = request.Data; server.NotifyAllClient(response);//广播 } else if (request.Type == "CreatChat") { NetResponse response = new NetResponse(); response.Type = request.Type; response.Code = 1; // 存储 this.Name = request.Data; // 发送数据 Send(response); //广播 NetResponse responseNotify = new NetResponse(); //responseNotify.Type = "In"; responseNotify.Data = this.Name; server.NotifyAllClient(responseNotify); } else if (request.Type == "PlayerData") { NetResponse res = new NetResponse(); res.Type = request.Type; ServerPlayerData serverplayerdata = new ServerPlayerData(); serverplayerdata.Account = new AccountInfo(UserName, Password); serverplayerdata.PlayerDataJson = request.Data; GameData.PlayerDataDic[UserName] = serverplayerdata;//### res.Code = 1; Send(res); } else if (request.Type == "In")//进入 { NetResponse response = new NetResponse(); response.Type = request.Type; response.Data = request.Data; response.Code = 1; server.NotifyAllClient(response); } else if (request.Type == "Out")//退出 { NetResponse response = new NetResponse(); response.Type = request.Type; response.Data = request.Data; response.Code = 1; server.NotifyAllClient(response); } else if (request.Type == "UseHorn")//喇叭 { Console.WriteLine("是不是没收到?"); NetResponse response = new NetResponse(); response.Type = request.Type; response.Data = request.Data; Send(response); } else if (request.Type == "Register") //注册 { NetResponse response = new NetResponse(); //回应 response.Type = request.Type; AccountInfo account = JsonConvert.DeserializeObject <AccountInfo>(request.Data); //密码长度 if (account.Password.Length < 3) { response.Code = -1; } else { if (GameData.AccountList.Count == 0) { GameData.AccountList.Add(account); response.Code = 1; } else { for (int i = 0; i < GameData.AccountList.Count; i++) { if (account.Username == GameData.AccountList[i].Username) { Console.WriteLine(account.Username); Console.WriteLine(GameData.AccountList[i].Username); response.Code = 0; break; } else { response.Code = 1; isOk = true; } } if (isOk) { GameData.AccountList.Add(account); } } } Send(response); } else if (request.Type == "Login")//登录 { AccountInfo account = JsonConvert.DeserializeObject <AccountInfo>(request.Data); //和服务器中存储的账号信息进行比对 for (int i = 0; i < GameData.AccountList.Count; i++) { if (GameData.AccountList[i].Username == account.Username && GameData.AccountList[i].Password == account.Password) { isOk = true; break; } } NetResponse res = new NetResponse(); res.Type = request.Type; //isOk = true;//测试代码 //发送回应 if (isOk) { res.Code = 1; // 通过账户名,找到对应的玩家数据,判断是否为Null; if (GameData.PlayerDataDic.ContainsKey(account.Username)) { res.Data = GameData.PlayerDataDic[account.Username].PlayerDataJson; } UserName = account.Username; Password = account.Password; //for (int i = 0; i < GameData.AccountList.Count; i++) //{ // // 判断密码的长度是否大于3 // if (GameData.AccountList[i].Password.Length < 3) // { // res.Code = -1; // } // else // { // res.Code = 1; // // 通过账户名,找到对应的玩家数据,判断是否为Null; // if (GameData.PlayerDataDic.ContainsKey(account.Username)) // { // res.Data = GameData.PlayerDataDic[account.Username].PlayerDataJson; // } // UserName = account.Username; // } //} } else { res.Code = 0; } Send(res); } else if (request.Type == "CreateRole")//创建角色 { ////拿到名字是否重名 //bool isOk = true; //NetResponse response = new NetResponse(); //response.Type = request.Type; //for (int i = 0; i < GameData.NameList.Count; i++) //{ // if (GameData.NameList[i] == request.Data) // { // isOk = false; // break; // } //} //// 如果不重名 //if (isOk) //{ // response.Code = 1; // // 存储 // this.Name = request.Data; // GameData.NameList.Add(Name); // // 发送数据 // Send(response); //} //else// 如果重名 //{ // response.Code = 0; // //发送数据 // Send(response); //} NetResponse res = new NetResponse(); res.Type = request.Type; string name = request.Data; for (int i = 0; i < GameData.AccountList.Count; i++) { if (GameData.PlayerDataDic.ContainsKey(GameData.AccountList[i].Username)) { ServerPlayerData player = GameData.PlayerDataDic[GameData.AccountList[i].Username]; JObject playerdataObj = JObject.Parse(player.PlayerDataJson); if (playerdataObj["Name"].ToString() == request.Data) { res.Code = 0; Send(res); return; } } } res.Code = 1; Send(res); } else if (request.Type == "Rank")//排行榜 { RolePower playerpower = JsonConvert.DeserializeObject <RolePower>(request.Data); Console.WriteLine(GameData.rolePowerList.Count); if (GameData.rolePowerList.Count == 0) { GameData.rolePowerList.Add(playerpower); } else { bool isok = false; for (int i = 0; i < GameData.rolePowerList.Count; i++) { if (playerpower.Name == GameData.rolePowerList[i].Name) { GameData.rolePowerList[i].Power = playerpower.Power; isok = true; break; } } if (!isok) { GameData.rolePowerList.Add(playerpower); isok = false; } } NetResponse response = new NetResponse(); response.Type = request.Type; Console.WriteLine(GameData.rolePowerList.Count); //遍历战力链表 List <RolePower> NowPowerList = new List <RolePower>(); for (int i = 0; i < GameData.rolePowerList.Count; i++) { Console.WriteLine("发送战力信息"); NowPowerList.Add(GameData.rolePowerList[i]); } response.Data = JsonConvert.SerializeObject(NowPowerList); Send(response); } }