public void PublishMessage(int newsId, int objId, object obj, MessageOperation operation) { string routingKey = GenerateRoutingKey(newsId, objId, obj, operation); byte[] data = SerializeObject(obj); PublishMessage(routingKey, data); }
static Message CreateMessage(MessageOperation operation, Guid workSessionID, string documentID) { Message message = CreateMessage(operation, new List <WorkSessionServerInfo>()); message.Sender.WorkSessions.GetOrAdd(workSessionID, new WorkSessionInfo(workSessionID, documentID)); return(message); }
private PlayersMessage CreatePlayerMessage(MessageOperation operation, IPlayerID playerID) { List <PlayerInfo> list = new List <PlayerInfo>(); PlayersMessage msg = (PlayersMessage)MessageFactory.Create(MessageType.Players); msg.Operation = (byte)operation; switch (operation) { case MessageOperation.List: foreach (IPlayerID pid in _players.Values) { if (pid.GetID() != playerID.GetID()) { ServerPlayerInfo spi = pid as ServerPlayerInfo; list.Add(spi.GePlayerInfo()); } } break; case MessageOperation.Add: list.Add(((ServerPlayerInfo)playerID).GePlayerInfo()); break; case MessageOperation.Remove: list.Add(((ServerPlayerInfo)playerID).GePlayerInfo()); break; case MessageOperation.Modify: list.Add(((ServerPlayerInfo)playerID).GePlayerInfo()); break; } msg.PlayerList = list; return(msg); }
public static MessageOperation FromBytes(byte[] buffer) { int bufferLength = buffer.Length; if (bufferLength < lengthID + lengthLength + 1)//1是 markStart { return(null); } MessageOperation message = new MessageOperation(); using (MemoryStream memoryStream = new MemoryStream(buffer)) //将字节数组填充至内存流 { BinaryReader binaryReader = new BinaryReader(memoryStream); //以二进制读取器读取该流内容 int mark = binaryReader.ReadByte(); //标志 message.Id = binaryReader.ReadBytes(lengthID); message.Length = binaryReader.ReadBytes(lengthLength); int dataLength = message.GetLength(); //如果【进来的Bytes长度】小于【一个完整的MessageXieYi长度】 if ((bufferLength - (lengthID + lengthLength)) < dataLength) { Console.WriteLine("数据接收不齐."); return(null); } message.Message = binaryReader.ReadBytes(dataLength); binaryReader.Close(); //关闭二进制读取器,是否资源 } return(message); //返回消息协议对象 }
public static MessageOperation FromBytes(int id, byte[] buffer) { if (buffer == null) { return(null); } int bufferLength = buffer.Length; int fillLength = bufferLength > lengthMessage ? lengthMessage : bufferLength; MessageOperation message = new MessageOperation(); using (MemoryStream memoryStream = new MemoryStream(buffer)) //将字节数组填充至内存流 { BinaryReader binaryReader = new BinaryReader(memoryStream); //以二进制读取器读取该流内容 message.Length = BitConverter.GetBytes(fillLength); message.Id = BitConverter.GetBytes(id); message.Message = binaryReader.ReadBytes(fillLength); binaryReader.Close(); //关闭二进制读取器,是否资源 } return(message); }
public WhatsAppOperation(WhatsAppConnect connect) { InstanceOperation = new InstanceOperation(connect); MessageOperation = new MessageOperation(connect); GroupsOperation = new GroupsOperation(connect); QueuesOperation = new QueuesOperation(connect); BannedOperation = new BannedOperation(connect); }
public Message(string roleInstanceId, string hostServerName, string hostServerIP, MessageOperation messageOperation, List <WorkSessionServerInfo> registeredServers) { RoleInstanceId = roleInstanceId; MessageOperation = messageOperation; AppendServers(registeredServers); SetSenderInfo(new WorkSessionServerInfo(roleInstanceId, hostServerName, hostServerIP)); CreateTime = DateTime.Now; }
static Message CreateMessage(MessageOperation operation, List <WorkSessionServerInfo> registeredServers) { var message = new Message( RoleEnvironment.CurrentRoleInstance.Id, System.Environment.MachineName, NetUtils.GetLocalIPAddress(), operation, registeredServers ); return(message); }
private static WorkSessionStatus GetStatusFromOperation(MessageOperation messageOperation) { switch (messageOperation) { case MessageOperation.AutoSaveWorkSession: return(WorkSessionStatus.AutoSaved); case MessageOperation.HibernateWorkSession: return(WorkSessionStatus.Hibernated); case MessageOperation.WakeUpWorkSession: return(WorkSessionStatus.WokenUp); case MessageOperation.AddWorkSession: return(WorkSessionStatus.Loaded); case MessageOperation.RemoveWorkSession: return(WorkSessionStatus.Removed); } return(WorkSessionStatus.Loaded); }
public static string GenerateRoutingKey(int newsId, int objId, object obj, MessageOperation operation) { string result = ""; result = "News." + newsId + "."; switch (operation) { case MessageOperation.Insert: result += "Insert."; break; case MessageOperation.Update: result += "Update."; break; case MessageOperation.Delete: result += "Delete."; break; default: result += "Update."; break; } result += obj.GetType().Name + "." + objId; return(result); }
public void Read(TProtocol iprot) { iprot.IncrementRecursionDepth(); try { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.List) { { Operations = new List <MessageOperation>(); TList _list17 = iprot.ReadListBegin(); for (int _i18 = 0; _i18 < _list17.Count; ++_i18) { MessageOperation _elem19; _elem19 = new MessageOperation(); _elem19.Read(iprot); Operations.Add(_elem19); } iprot.ReadListEnd(); } } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.Bool) { EndFlag = iprot.ReadBool(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); } finally { iprot.DecrementRecursionDepth(); } }
static void NotifyServers(MessageOperation operation) { WorkSessionMessenger.SendMessage(operation, new List <WorkSessionServerInfo>()); }
public MessageOperationCheckAttribute(MessageOperation op, string param = "id") { this.op = op; this.param = param; }
public static void AddError(this ValidationResult valid, ValidationKey key, string parameter = null) { AddError(valid, key.ToString(), () => MessageOperation.GetValidationMessage(key, parameter)); }
public async Task ReadAsync(TProtocol iprot, CancellationToken cancellationToken) { iprot.IncrementRecursionDepth(); try { TField field; await iprot.ReadStructBeginAsync(cancellationToken); while (true) { field = await iprot.ReadFieldBeginAsync(cancellationToken); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.List) { { TList _list166 = await iprot.ReadListBeginAsync(cancellationToken); Operations = new List <MessageOperation>(_list166.Count); for (int _i167 = 0; _i167 < _list166.Count; ++_i167) { MessageOperation _elem168; _elem168 = new MessageOperation(); await _elem168.ReadAsync(iprot, cancellationToken); Operations.Add(_elem168); } await iprot.ReadListEndAsync(cancellationToken); } } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 2: if (field.Type == TType.Bool) { EndFlag = await iprot.ReadBoolAsync(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; default: await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); break; } await iprot.ReadFieldEndAsync(cancellationToken); } await iprot.ReadStructEndAsync(cancellationToken); } finally { iprot.DecrementRecursionDepth(); } }
public ServiceResponse ChangePassword(int userId, string oldPassword, string newPassword, string repeatNewPassword) { User user = GetUserById(userId); if (user == null) { return(new ServiceResponse(ServiceRespondStatus.Error, ValidationKey.NullUser.ToString(), MessageOperation.GetValidationMessage(ValidationKey.NullUser))); } ValidationResult passwordValidate = userServiceValidation.ChangePassword(user.Password, oldPassword, newPassword, repeatNewPassword); if (!passwordValidate.IsSucces) { return(new ServiceResponse(ServiceRespondStatus.Error, passwordValidate.ErrorList)); } user.Password = HashEncryption.Hash(newPassword); context.SaveChanges(); return(new ServiceResponse()); }
public static void AddError(this ValidationResult valid, ValidationKey key, IEnumerable <string> parameterList) { AddError(valid, key.ToString(), () => MessageOperation.GetValidationMessage(key, parameterList)); }
public static void SendMessage(MessageOperation operation, Guid workSessionID, string documentID) { var message = CreateMessage(operation, workSessionID, documentID); InterRoleCommunicator.SendMessage(message); }
public static void SendMessage(MessageOperation operation, List <WorkSessionServerInfo> registeredServers) { var message = CreateMessage(operation, registeredServers); InterRoleCommunicator.SendMessage(message); }
//public static object RunOperation(Selection query, Response context) //{ // bool? result = null; // var arguments = query.Arguments; // var incomplete_operation = arguments["incomplete_operation"].Get<Id64>(); // while (true) // try { // using (var scope = new TransactionScope()) { // using (var conn = Core.GetDbConnection(context.Session)) // { // var msg = conn.Query<MessageOperation,Address, MessageOperation>("run_operation", (task, address) => // { // return task; // }, // new {_incomplete_operation = incomplete_operation, _user = context.Session.User}, // commandType: CommandType.StoredProcedure); // Debug.WriteLine(JsonConvert.SerializeObject(msg.First())); // Core.PlcClient.AddMSg(msg.First()); // scope.Complete(); // } // } // return true; // } // catch (Exception e) { // switch (e) { // case PostgresException pgException when pgException.SqlState == "40001": // Debug.WriteLine("40001"); // break; // case TransactionAbortedException tranException // when tranException.InnerException is PostgresException pgException && // pgException.SqlState == "40001": // Debug.WriteLine("40001"); // break; // default: // Debug.WriteLine(e); // context.AddError(query.ToString(), e.Message); // return null; // } // } //} public static object RunOperation(Selection query, Response context) { var arguments = query.Arguments; var uncommittedOperation = arguments["uncommitted_operation"].Get <Id64>(); MessageOperation msg = null; var repeat = true; while (repeat) { try { using (var scope = new TransactionScope()) { using var connection = Core.GetNpgsqlConnection(context.Session); connection.Open(); using (var command = new NpgsqlCommand("run_operation", connection)) { command.Parameters.AddWithValue("_uncommitted_operation", (long)uncommittedOperation); command.Parameters.AddWithValue("_user", (long)context.Session.User); command.CommandType = CommandType.StoredProcedure; using var reader = command.ExecuteReader(); reader.Read(); msg = new MessageOperation( (Id64)(long)reader.GetValue(0), (Id64)(long)reader.GetValue(1), (Id64)(long)reader.GetValue(3), reader.GetFieldValue <OperationTypes>(2), reader.GetFieldValue <AddressDefinition>(4), reader.GetFieldValue <AddressDefinition>(5), reader.GetFieldValue <AddressDefinition>(6), reader.GetFieldValue <short>(7)); } scope.Complete(); } repeat = false; } catch (Exception e) { switch (e) { case PostgresException pgException when pgException.SqlState == "40001": Debug.WriteLine("40001"); break; case TransactionAbortedException tranException when tranException.InnerException is PostgresException pgException && pgException.SqlState == "40001": Debug.WriteLine("40001"); break; default: Debug.WriteLine(e); context.AddError(query.ToString(), e.Message); return(null); } } } if (msg.IsVirtual == 1) { repeat = true; while (repeat) { try { using (var scope = new TransactionScope()) { using var connection = Core.GetDbConnection(); connection.Execute("done_operation", new { _uncommitted_operation = uncommittedOperation }, commandType: CommandType.StoredProcedure); scope.Complete(); } repeat = false; } catch (Exception e) { switch (e) { case PostgresException pgException when pgException.SqlState == "40001": Debug.WriteLine("40001"); break; case TransactionAbortedException tranException when tranException.InnerException is PostgresException pgException && pgException.SqlState == "40001": Debug.WriteLine("40001"); break; default: Debug.WriteLine(e); context.AddError(query.ToString(), e.Message); return(null); } } } return(true); } try { Core.PlcClient.AddMSg(msg); return(true); } catch (Exception) { // ignored } return(null); }
///// <summary> ///// 同步发送方法 ///// </summary> ///// <param name="e"></param> ///// <param name="timeout">同步发送的延迟毫秒</param> //public void Send(AsyncUserToken e, byte[] data) //{ // AsyncUserToken userToken = e; // try // { // //if (!userToken.ConnectSocket.Connected) // //{ // // OffLineClientSocket(userToken); // //} // userToken.ConnectSocket.SendTimeout = 0; // //int startTickCount = Environment.TickCount; // try // { // userToken.ConnectSocket.Send(data, data.Length, SocketFlags.None); // } // catch (SocketException ex) // { // if ( // ex.SocketErrorCode == SocketError.WouldBlock // || ex.SocketErrorCode == SocketError.IOPending // || ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable // ) // { // // socket buffer is probably full, wait and try again // Thread.Sleep(30); // // // Log4Debug("发送失败?"); // } // else // { // OffLineClientSocket(userToken); // /*throw ex;*/ // any serious error occurr // } // } // } // catch (Exception error) // { // Log4Debug("SendError:" + error.Message); // OffLineClientSocket(userToken); // } //} public void Send(AsyncUserToken userToken) { Socket socket = userToken.ConnectSocket; //判断Socket是否存在以及是否掉线 if (socket == null) { if (userToken.userInfo != null) { instance.Log4Debug("玩家掉线:" + userToken.userInfo.Register.name); userToken.userInfo.CurState = RoomActorState.Offline; } return; } else if (!socket.Connected)//发送数据时检测到Socket掉线 { return; } //开始发送 socket.SendTimeout = 10000;//设置发送后判断超时的时长 while (userToken.SendBuffer.Count > 0) { byte[] mix = new byte[userToken.SendBuffer.Count]; lock (userToken.SendBuffer) { Array.Copy(userToken.SendBuffer.ToArray(), 0, mix, 0, userToken.SendBuffer.Count); userToken.ClearSend(); } //int startTickCount = Environment.TickCount; while (mix.Length > 0) { int curIndex = userToken.sendIndex; MessageOperation oper = MessageOperation.FromBytes(curIndex, mix); byte[] buffer = null; buffer = oper.ToBytes(); userToken.sendIndex++; mix = mix.Skip(buffer.Length).ToArray(); string sendIfo = "userToken.sendIndex:" + curIndex + "----"; for (int i = 0; i < buffer.Length; i++) { sendIfo += buffer[i] + ","; } Log4Debug(sendIfo); //byte[] idBuffer = BitConverter.GetBytes(curIndex);// 将 int 转换成字节数组 //byte[] lengthBuffer = new byte[4]; //userToken.sendIndex++; //int dealLength = 0; //if (mix.Length > 1020) //{ // dealLength = 1020; //} //else //{ // dealLength = mix.Length; //} //byte[] buffer = new byte[idBuffer.Length + dealLength]; //Array.Copy(idBuffer, 0, buffer, 0, idBuffer.Length);//4 //Array.Copy(mix, 0, buffer, idBuffer.Length, dealLength);//dealLength //mix = mix.Skip(buffer.Length).ToArray(); //string sendIfo = "userToken.sendIndex:" + curIndex + "----"; //for (int i = 0; i < buffer.Length; i++) //{ // sendIfo += buffer[i] + ","; //} //Log4Debug(sendIfo); // int sent = 0; // how many bytes is already sent do { try { sent += socket.Send(buffer, sent, buffer.Length - sent, SocketFlags.None); } catch (SocketException ex) { Log4Debug("sendError:" + ex.SocketErrorCode); // if (ex.SocketErrorCode == SocketError.WouldBlock || ex.SocketErrorCode == SocketError.IOPending || ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable) { // socket buffer is probably full, wait and try again Thread.Sleep(30); Log4Debug("睡眠30秒后继续发送。"); } else { if (ex.SocketErrorCode == SocketError.ConnectionAborted)//您的主机中的软件中止了一个已建立的连接。 { return; } //throw ex; // any serious error occurr Log4Debug("send错误:" + ex.Message); } } } while (sent < buffer.Length); //Log4Debug("发送用时毫秒:" + (Environment.TickCount - startTickCount)); } } userToken.isDealSend = false; }
private void ReceiveCallback(IAsyncResult ar) { AsyncUserToken userToken = (AsyncUserToken)ar.AsyncState; Socket socket = userToken.ConnectSocket; try { if (socket == null || !socket.Connected) { return; } lock (userToken.ReceiveBuffer) { //从远程设备读取数据 int read = socket.EndReceive(ar); if (read > 0) { //byte[] buffer = new byte[read]; ////将getBuffer数组的前read个字节拷贝到buffer数组中 //Array.Copy(userToken.AsyncReceiveBuffer, 0, buffer, 0, read); //userToken.userInfo.heartbeatTime = DateTime.Now; ////接收数据保存以后继续接收 //ProcessReceive(userToken); //lock (userToken.ReceiveBuffer) //{ // //存值 // for (int i = 0; i < buffer.Length; i++) // { // //将buffer保存到队列 // userToken.ReceiveBuffer.Enqueue(buffer[i]); // } //} //if (!userToken.isDealReceive) //{ // userToken.isDealReceive = true; // Handle(userToken); //} byte[] buffer = new byte[read]; //将getBuffer数组的前read个字节拷贝到buffer数组中 Array.Copy(userToken.AsyncReceiveBuffer, 0, buffer, 0, read); //接收数据保存以后继续接收 ProcessReceive(userToken); string info = ""; for (int i = 0; i < buffer.Length; i++) { info += buffer[i] + ","; } //Log4Debug("接收数据:" + info); MessageOperation oper = MessageOperation.FromBytes(buffer); userToken.outOrders.Add(oper.GetId(), oper.Message); //byte[] intBuff = new byte[4] { buffer[0], buffer[1], buffer[2], buffer[3] }; //int index = BitConverter.ToInt32(intBuff, 0); // 从字节数组转换成 int //byte[] dealBuffer = new byte[buffer.Length - intBuff.Length]; //Array.Copy(buffer, intBuff.Length, dealBuffer, 0, dealBuffer.Length); //userToken.outOrders.Add(index, dealBuffer); //while (userToken.outOrders.ContainsKey(userToken.sendIndex)) //{ // //存值 // for (int i = 0; i < userToken.outOrders[userToken.sendIndex].Length; i++) // { // //将buffer保存到队列 // userToken.ReceiveBuffer.Enqueue(userToken.outOrders[userToken.sendIndex][i]); // } // userToken.sendIndex++; //} if (!userToken.isDealReceive) { userToken.isDealReceive = true; Handle(userToken); } } else//接收数据小于等于0 { CloseClientSocket(userToken); return; } } } catch (Exception error) { Log4Debug("ReceiveError:" + error.Message); CloseClientSocket(userToken); } }