public static async Task Run( [QueueTrigger("%Storage:BlockQueue%", Connection = "Storage:Connection")] BlockMessage message, [Queue("%Storage:BlockQueue%", Connection = "Storage:Connection")] CloudQueue blockQueue, [Queue("%Storage:ContractQueue%", Connection = "Storage:Connection")] CloudQueue contractQueue, ILogger log, ExecutionContext context) { IConfigurationRoot config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var web3 = new Web3(config.GetValue<string>("Blockchain:Endpoint")); var block = await web3.Eth.Blocks.GetBlockWithTransactionsByNumber.SendRequestAsync(new HexBigInteger(message.Block)); if (block.Transactions.Length > 0) { foreach (var tx in block.Transactions) { if (tx.To != null) { continue; } var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(tx.TransactionHash); string cMsg = JsonConvert.SerializeObject(new ContractMessage { Address = receipt.ContractAddress, TxHash = tx.TransactionHash }); await contractQueue.AddMessageAsync(new CloudQueueMessage(cMsg)); } } }
private bool ProcessMessage_OBD(BlockMessage obd_msg, ref BlockMessage ResponseMessage) { bool bRet = false; switch ((ENUM_SID)obd_msg.GetSID()) { case ENUM_SID.ReadDiagnosticTroubleCodesByStatus: List <byte> in_list = obd_msg.GetDataList(); ReadDiagnosticTroubleCodesByStatus_OBD_StatusOfDTC = (uint)in_list.IndexOf(0); ReadDiagnosticTroubleCodesByStatus_OBD_GroupOfDTC = (uint)in_list.IndexOf(1) + ((uint)in_list.IndexOf(2)) << 8; PrepareResponse_ReadDiagnosticTroubleCodesByStatus_OBD(obd_msg, ref ResponseMessage); bRet = true; break; case ENUM_SID.StartCommunication: PrepareResponse_StartCommunication_OBD(obd_msg, ref ResponseMessage); bRet = true; break; case ENUM_SID.StopCommunication: PrepareResponse_StopCommunication_OBD(obd_msg, ref ResponseMessage); bRet = true; break; default: break; } return(bRet); }
public void ProcessMessage(PeerConnection peer, MineralMessage message) { BlockMessage block_message = (BlockMessage)message; Check(peer, block_message); BlockId block_id = block_message.Block.Id; Item item = new Item(block_id, InventoryType.Block); if (peer.SyncBlockRequest.ContainsKey(block_id)) { peer.SyncBlockRequest.TryRemove(block_id, out _); Manager.Instance.SyncService.ProcessBlock(peer, block_message); } else { peer.InventoryRequest.TryGetValue(item, out long ms); Logger.Info( string.Format("Receive block {0} from {1}, cost {2}ms", block_id.GetString(), peer.Address, Helper.CurrentTimeMillis() - ms)); peer.InventoryRequest.TryRemove(item, out _); ProcessBlock(peer, block_message.Block); } }
private BlockMessage PrepareResponse_ReadDiagnosticTroubleCodesByStatus_ABS(BlockMessage in_msg, ref BlockMessage out_msg) { List <byte> out_list = GenerateQueuedResponseData_ABS(); out_msg = new BlockMessage((byte)((((uint)MSG_A1A0_MODE.WITH_ADDRESS_INFO) << 6)), in_msg.GetSA(), in_msg.GetTA(), (byte)(in_msg.GetSID() | RETURN_SID_OR_VALUE), out_list, true); // for format_4 return(out_msg); }
private BlockMessage PrepareResponse_StopCommunication_ABS(BlockMessage in_msg, ref BlockMessage out_msg) { List <byte> out_list = new List <byte>(); out_msg = new BlockMessage((byte)((((uint)MSG_A1A0_MODE.WITH_ADDRESS_INFO) << 6)), in_msg.GetSA(), in_msg.GetTA(), (byte)(in_msg.GetSID() | RETURN_SID_OR_VALUE), out_list, true); // for format_4 return(out_msg); }
public void Broadcast(Message message) { if (Args.Instance.IsFastForward && !(message is BlockMessage)) { return; } if (this.inventory_spread.Count > this.max_spread_size) { Logger.Warning( string.Format("Drop message, type: {0}, ID: {1}.", message.Type, message.MessageId)); return; } Item item = null; if (message is BlockMessage) { BlockMessage block_message = (BlockMessage)message; item = new Item(block_message.MessageId, InventoryType.Block); Logger.Info("Ready to broadcast block " + block_message.Block.Id.GetString()); block_message.Block.Transactions.ForEach(tx => { var find = this.inventory_spread.FirstOrDefault(pair => pair.Key.Hash == tx.Id); if (!find.Equals(default(KeyValuePair <Item, long>))) { this.inventory_spread.TryRemove(find.Key, out _); this.transaction_cache.Add(new Item(find.Key.Hash, InventoryType.Trx).ToString(), new TransactionMessage(tx.Instance)); } }); this.block_cache.Add(item.ToString(), message); } else if (message is TransactionMessage) { TransactionMessage tx_message = (TransactionMessage)message; item = new Item(tx_message.MessageId, InventoryType.Trx); this.tx_count.Add(); this.transaction_cache.Add(item.ToString(), new TransactionMessage(((TransactionMessage)message).Transaction.Instance)); } else { Logger.Error("Adv item is neither block nor trx, type : " + message.Type.ToString()); return; } this.inventory_spread.TryAdd(item, Helper.CurrentTimeMillis()); if (item.Type == InventoryType.Block) { ConsumerInventoryToSpread(); } }
public void CreateMessageWithBlock() { Block block = FactoryHelper.CreateGenesisBlock(); BlockMessage message = new BlockMessage(block); Assert.AreSame(block, message.Block); Assert.AreEqual(MessageType.BlockMessage, message.MessageType); }
private void HandleSyncBlock() { lock (this.block_just_receive) { foreach (var received in this.block_just_receive) { this.block_wait_process.TryAdd(received.Key, received.Value); } this.block_just_receive.Clear(); } bool is_processed = true; while (is_processed) { is_processed = false; Logger.Refactoring("HandleSyncBlock()"); Logger.Refactoring( string.Format("block wait process {0}", this.block_wait_process.Count)); foreach (KeyValuePair <BlockMessage, PeerConnection> process in this.block_wait_process.OrderBy(block => block.Key.Block.Num)) { BlockMessage message = process.Key; PeerConnection peer = process.Value; if (peer.IsDisconnect) { this.block_wait_process.TryRemove(message, out _); Invalid(message.Block.Id); return; } bool is_found = false; var peers = Manager.Instance.NetDelegate.ActivePeers.Where(p => { p.SyncBlockFetch.TryPeekLeft(out BlockId id); return(message.Block.Id.Equals(id)); }); foreach (PeerConnection p in peers) { p.SyncBlockFetch.TryPopLeft(out _); p.SyncBlockProcess.Add(message.Block.Id); is_found = true; } if (is_found) { this.block_wait_process.TryRemove(message, out _); is_processed = true; ProcessSyncBlock(message.Block); } } } }
private BlockMessage PrepareNegativeResponse_MsgErrort_ReadDiagnosticTroubleCodesByStatus_ABS(BlockMessage in_msg, ref BlockMessage out_msg) { List <byte> out_list = new List <byte>(); out_list.Add(in_msg.GetSID()); out_list.Add(NegativeResponse_MsgError_ReadDiagnosticTroubleCodesByStatus_ResponseCode); out_msg = new BlockMessage((byte)((((uint)MSG_A1A0_MODE.WITH_ADDRESS_INFO) << 6)), in_msg.GetSA(), in_msg.GetTA(), NEGATIVE_RESPONSE_SID, out_list, true); // for format_4 return(out_msg); }
private BlockMessage PrepareResponse_StartCommunication_OBD(BlockMessage in_msg, ref BlockMessage out_msg) { List <byte> out_list = new List <byte>(); out_list.Add((byte)(OBD_KeyByte_for_StartCommunication & 0xff)); out_list.Add((byte)((OBD_KeyByte_for_StartCommunication >> 8) & 0xff)); out_msg = new BlockMessage((byte)((((uint)MSG_A1A0_MODE.WITH_ADDRESS_INFO) << 6)), in_msg.GetSA(), in_msg.GetTA(), (byte)(in_msg.GetSID() | RETURN_SID_OR_VALUE), out_list, false); // for format_2 return(out_msg); }
public void ProcessBlockMessage() { BlockProcessor blockProcessor = FactoryHelper.CreateBlockProcessor(); Block block = FactoryHelper.CreateGenesisBlock(); BlockMessage message = new BlockMessage(block); MessageProcessor processor = new MessageProcessor(blockProcessor, null); processor.ProcessMessage(message); Assert.IsNotNull(blockProcessor.BlockChain); Assert.AreEqual(block.Number, blockProcessor.BlockChain.BestBlockNumber); Assert.AreEqual(block, blockProcessor.BlockChain.GetBlock(0)); }
public bool ProcessMessage(BlockMessage in_msg, ref BlockMessage out_msg) { bool bRet = false; if (in_msg.GetTA() == ADDRESS_ABS) { bRet = ProcessMessage_ABS(in_msg, ref out_msg); } else if (in_msg.GetTA() == ADDRESS_OBD) { bRet = ProcessMessage_OBD(in_msg, ref out_msg); } return(bRet); }
private void SendMessage(string message) { var hash = chain.CreateBlock(message); var blockMessage = new BlockMessage() { Message = message, Hash = hash }; chatClient.SendMessage(new Message() { Command = "Text", Parameters = JsonConvert.SerializeObject(blockMessage) }).Wait(); chain.AddBlock(message, hash); }
public bool ProcessMessage(BlockMessage in_msg, ref BlockMessage out_msg) { bool bRet = false; if (in_msg.GetTA() == ADDRESS_ABS) { bRet = ProcessMessage_ABS(in_msg, ref out_msg); } else if (in_msg.GetTA() == ADDRESS_OBD) { bRet = ProcessMessage_OBD(in_msg, ref out_msg); } OBD_DTC_Data_Queue.Clear(); ABS_DTC_Data_Queue.Clear(); return(bRet); }
private void BroadcastNewBlock(object sender, BlockEventArgs e) { if (e == null) { throw new ArgumentNullException(nameof(e)); } if (e.Data == null) { throw new ArgumentNullException(nameof(e.Data)); } var blockMessage = new BlockMessage(e.Data, _network); Broadcast(blockMessage); }
public Message GetData(SHA256Hash hash, InventoryType type) { Message result = null; try { switch (type) { case InventoryType.Block: { result = new BlockMessage(Manager.Instance.DBManager.GetBlockById(hash)); } break; case InventoryType.Trx: { TransactionCapsule tx = Manager.Instance.DBManager.Transaction.Get(hash.Hash); if (tx == null) { throw new StoreException(); } result = new TransactionMessage(tx.Instance); } break; default: { throw new StoreException(); } } } catch (StoreException e) { throw new P2pException(Exception.P2pException.ErrorType.DB_ITEM_NOT_FOUND, "type: " + type + ", hash: " + hash.Hash.ToHexString(), e); } return(result); }
private void Tmr_FetchingUARTInput_Tick(object sender, EventArgs e) { // Regularly polling request message while (MySerialPort.KLineBlockMessageList.Count() > 0) { // Pop 1st KLine Block Message BlockMessage in_message = MySerialPort.KLineBlockMessageList[0]; MySerialPort.KLineBlockMessageList.RemoveAt(0); // Display debug message on RichTextBox String raw_data_in_string = MySerialPort.KLineRawDataInStringList[0]; MySerialPort.KLineRawDataInStringList.RemoveAt(0); DisplayKLineBlockMessage(rtbKLineData, "raw_input: " + raw_data_in_string); DisplayKLineBlockMessage(rtbKLineData, "In - " + in_message.GenerateDebugString()); // Process input Kline message and generate output KLine message KWP_2000_Process kwp_2000_process = new KWP_2000_Process(); BlockMessage out_message = new BlockMessage(); //Use_Random_DTC(kwp_2000_process); // Random Test //Use_Fixed_DTC_from_HQ(kwp_2000_process); // Simulate response from a ECU device Scan_DTC_from_UI(kwp_2000_process); // Scan Checkbox status and add DTC into queue // Generate output block message according to input message and DTC codes kwp_2000_process.ProcessMessage(in_message, ref out_message); // Convert output block message to List<byte> so that it can be sent via UART List <byte> output_data; out_message.GenerateSerialOutput(out output_data); // NOTE: because we will also receive all data sent by us, we need to tell UART to skip all data to be sent by SendToSerial MySerialPort.Add_ECU_Filtering_Data(output_data); MySerialPort.Enable_ECU_Filtering(true); // Send output KLine message via UART (after some delay) Thread.Sleep((KWP_2000_Process.min_delay_before_response - 1)); MySerialPort.SendToSerial(output_data.ToArray()); // Show output KLine message for debug purpose DisplayKLineBlockMessage(rtbKLineData, "Out - " + out_message.GenerateDebugString()); } }
public void ProcessBlock(PeerConnection peer, BlockMessage message) { lock (this.block_just_receive) { this.block_just_receive.TryAdd(message, peer); } this.is_handle = true; if (peer.IsIdle) { if (peer.RemainNum > 0 && peer.SyncBlockFetch.Count <= Parameter.NodeParameters.SYNC_FETCH_BATCH_NUM) { SyncNext(peer); } else { this.is_fetch = true; } } }
private static void DataReceivedHandler_KLine(object sender, SerialDataReceivedEventArgs e) { // Find out which serial port --> which myserial SerialPort sp = (SerialPort)sender; MySerialDictionary.TryGetValue(sp.PortName, out Object myserial_serial_obj); MySerial myserial = (MySerial)myserial_serial_obj; while (sp.BytesToRead > 0) { // Read in all char bool IsMessageReady = false; byte byte_data = (byte)sp.ReadByte(); if (myserial.ECU_filtering == true) { if (myserial.ECU_data_to_be_filtered.Count > 0) { myserial.ECU_data_to_be_filtered.RemoveAt(0); } if (myserial.ECU_data_to_be_filtered.Count == 0) { myserial.ECU_filtering = false; } } else { myserial.RawDataInString += byte_data.ToString("X2") + " "; IsMessageReady = myserial.KLineKWP2000Process.ProcessNextByte(byte_data); if (IsMessageReady) { BlockMessage new_message = myserial.KLineKWP2000Process.GetProcessedBlockMessage(); myserial.KLineBlockMessageList.Add(new_message); myserial.KLineRawDataInStringList.Add(myserial.RawDataInString); myserial.RawDataInString = ""; IsMessageReady = false; //break; } } } }
private void Check(PeerConnection peer, BlockMessage msg) { Item item = new Item(msg.Block.Id, InventoryType.Block); if (!peer.SyncBlockRequest.ContainsKey(msg.Block.Id) && !peer.InventoryRequest.ContainsKey(item)) { throw new P2pException( P2pException.ErrorType.BAD_MESSAGE, "no request"); } if (msg.Block.Instance.CalculateSize() > this.max_block_size) { throw new P2pException( P2pException.ErrorType.BAD_MESSAGE, "block size over limit"); } long gap = msg.Block.Timestamp - Helper.CurrentTimeMillis(); if (gap >= Parameter.ChainParameters.BLOCK_PRODUCED_INTERVAL) { throw new P2pException( P2pException.ErrorType.BAD_MESSAGE, "block time error"); } }
private void Launch(PeerConnector peerConnector, BlockMessage message) { peerConnector.Execute(message.Serialize()); }
public Message Parse(byte[] payload) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } if (payload.Length < 24) { throw new ParseMessageException(ErrorCodes.InvalidCommandLength); } var header = payload.Take(40); // Extract the header. var startStringPayload = header.Take(4); var network = Networks.MainNet; if (startStringPayload.SequenceEqual(new byte[] { 0xf9, 0xbe, 0xb4, 0xd9 })) { network = Networks.MainNet; } else if (startStringPayload.SequenceEqual(new byte[] { 0x0b, 0x11, 0x09, 0x07 })) { network = Networks.TestNet; } else if (startStringPayload.SequenceEqual(new byte[] { 0xfa, 0xbf, 0xb5, 0xda })) { network = Networks.RegTest; } else { throw new ParseMessageException(ErrorCodes.InvalidStartString); } var commandNamePayload = header.Skip(4).Take(12).Where(b => b != 0x00).ToArray(); var commandName = System.Text.Encoding.ASCII.GetString(commandNamePayload); var ipv6 = header.Skip(16).Take(16); var payloadSizePayload = header.Skip(32).Take(4).ToArray(); var payloadSize = BitConverter.ToInt32(payloadSizePayload, 0); var checkSum = header.Skip(36).Take(4); byte[] contentPayload = null; if (payloadSize > 0) { contentPayload = payload.Skip(40).Take(payloadSize).ToArray(); SHA256 mySHA256 = SHA256.Create(); var newCheckSum = mySHA256.ComputeHash(mySHA256.ComputeHash(contentPayload)).Take(4); if (!newCheckSum.SequenceEqual(checkSum)) { throw new ParseMessageException(ErrorCodes.InvalidChecksum); } } else if (!checkSum.SequenceEqual(new byte[] { 0x5d, 0xf6, 0xe0, 0xe2 })) { throw new ParseMessageException(ErrorCodes.InvalidChecksum); } if (!Constants.MessageNameLst.Contains(commandName)) { throw new ParseMessageException(ErrorCodes.InvalidCommandName); } Message message = null; if (commandName == Constants.MessageNames.Ping) { var nonce = BitConverter.ToUInt64(contentPayload, 0); message = new PingMessage(nonce, network); } else if (commandName == Constants.MessageNames.Addr) { message = AddrMessage.Deserialize(contentPayload, network); } else if (commandName == Constants.MessageNames.Version) { message = VersionMessage.Deserialize(contentPayload, network); } else if (commandName == Constants.MessageNames.Verack) { message = new VerackMessage(network); } else if (commandName == Constants.MessageNames.GetAddr) { message = new GetAddressMessage(network); } else if (commandName == Constants.MessageNames.Inventory) { message = InventoryMessage.Deserialize(contentPayload, network); } else if (commandName == Constants.MessageNames.Transaction) { message = TransactionMessage.Deserialize(contentPayload, network, Transactions.TransactionTypes.NoneCoinbase); } else if (commandName == Constants.MessageNames.Pong) { var nonce = BitConverter.ToUInt64(contentPayload, 0); message = new PongMessage(nonce, network); } else if (commandName == Constants.MessageNames.MemPool) { message = new MemPoolMessage(network); } else if (commandName == Constants.MessageNames.GetData) { message = GetDataMessage.Deserialize(contentPayload, network); } else if (commandName == Constants.MessageNames.Block) { message = BlockMessage.Deserialize(contentPayload, network); } else if (commandName == Constants.MessageNames.GetBlocks) { message = GetBlocksMessage.Deserialize(contentPayload, network); } else if (commandName == Constants.MessageNames.NotFound) { message = NotFoundMessage.Deserialize(contentPayload, network); } message.MessageHeader.Ipv6 = ipv6.ToArray(); return(message); }
/// <summary> /// The node received a block. /// </summary> async ValueTask <bool> INetworkMessageHandler <BlockMessage> .ProcessMessageAsync(BlockMessage message, CancellationToken cancellation) { int protocolVersion = PeerContext.NegotiatedProtocolVersion.Version; BlockHeader header = message.Block !.Header !; header.Hash = _blockHeaderHashCalculator.ComputeHash(header, protocolVersion); // compute transaction hashes in parallel to speed up the operation and check sent headers are sequential. Parallel.ForEach(message.Block.Transactions !, transaction => { transaction.Hash = _transactionHashCalculator.ComputeHash(transaction, protocolVersion); transaction.WitnessHash = _transactionHashCalculator.ComputeWitnessHash(transaction, protocolVersion); }); eventBus.Publish(new BlockReceived(message.Block !, PeerContext, this)); //enqueue headers for validation await _blockValidator.RequestValidationAsync(new BlockToValidate(message.Block !, PeerContext)).ConfigureAwait(false); return(true); }
/// <summary> /// Handles all actions for recieving data messages (Such as movement, block placing, etc) /// </summary> /// <param name="inc">The incoming message</param> private void ProcessDataMessage(NetIncomingMessage inc) { Player sender = Server.PlayerFromRUI(inc.SenderConnection.RemoteUniqueIdentifier, true); Map map = null; if (sender != null) { map = (Map)sender.Map; } MessageTypes type = (MessageTypes)Enum.Parse(typeof(MessageTypes), inc.ReadByte().ToString()); switch (type) { //When a player request to recieve a message case MessageTypes.Request: { MessageTypes request = new RequestMessage(inc).RequestType; //Request to recieve lobby data if (request == MessageTypes.Lobby) { List <LobbySaveData> rooms = new List <LobbySaveData>(); foreach (Map m in Maps) { rooms.Add(LobbySaveData.FromMap(m)); } LobbyMessage msg = new LobbyMessage(Server.Config.Name, Server.Config.Decription, Server.Config.Intro, NetworkManager.NetServer.ConnectionsCount, rooms); NetManager.Send(msg, inc.SenderConnection); } break; } //When a player exits to the lobby case MessageTypes.PlayerLeave: { PlayerLeaveMessage user = new PlayerLeaveMessage(inc); user.ID = sender.ID; Log.WriteLine(LogType.Room, "{0} has left: {1}", sender.Username, sender.Map.Name); //Remove player map.Players.Remove(sender); RebuildIndexes(map); //Send to players NetManager.Broadcast(sender.Map, new PlayerLeaveMessage(sender.ID)); IO.SaveMap((Bricklayer.Server.World.Map)sender.Map); sender = null; break; } //When a player moves case MessageTypes.PlayerStatus: { PlayerStateMessage state = new PlayerStateMessage(inc); state.ID = sender.ID; //Clamp position in bounds state.Position = new Point((int)MathHelper.Clamp(state.Position.X, Tile.Width, (map.Width * Tile.Width) - (Tile.Width * 2)), (int)MathHelper.Clamp(state.Position.Y, Tile.Height, (map.Height * Tile.Height) - (Tile.Height * 2))); sender.SimulationState.Position = state.Position.ToVector2(); sender.SimulationState.Velocity = state.Velocity.ToVector2(); sender.SimulationState.Movement = state.Movement.ToVector2(); sender.IsJumping = state.IsJumping; NetManager.BroadcastExcept(state, sender); break; } //When a player places a block case MessageTypes.Block: { BlockMessage state = new BlockMessage(inc); BlockType block = BlockType.FromID(state.BlockID); //Verify Block (Make sure it is in bounds and it has changed, no use sending otherwise) //TODO: Punish players spamming invalid data (Because official client should never send it) if (map.InBounds(state.X, state.Y, state.Z) && map.Tiles[state.X, state.Y, state.Z].Block.ID != block.ID) { map.Tiles[state.X, state.Y, state.Z].Block = block; NetManager.Broadcast(sender.Map, state); } break; } //When a player sends a chat message case MessageTypes.Chat: { ChatMessage chat = new ChatMessage(inc); chat.ID = sender.ID; //Verify length if (chat.Message.Length > ChatMessage.MaxLength) { chat.Message = chat.Message.Truncate(ChatMessage.MaxLength); } NetManager.BroadcastExcept(chat, sender); //Log message Log.WriteLine(LogType.Chat, ConsoleColor.Gray, "<{0}> {1}", sender.Username, chat.Message); break; } //When a player changes smiley case MessageTypes.PlayerSmiley: { PlayerSmileyMessage smiley = new PlayerSmileyMessage(inc); smiley.ID = sender.ID; if (sender.Smiley != smiley.Smiley) { sender.Smiley = smiley.Smiley; NetManager.BroadcastExcept(smiley, sender); } break; } //When a player changes mode (Ex: godmode to normal case MessageTypes.PlayerMode: { PlayerModeMessage mode = new PlayerModeMessage(inc); mode.ID = sender.ID; if (sender.Mode != mode.Mode) { sender.Mode = mode.Mode; NetManager.BroadcastExcept(mode, sender); } break; } //When a player requests to join a room case MessageTypes.JoinRoom: { if (sender == null) //If the sender isn't null, then they are already in a room { JoinRoomMessage msg = new JoinRoomMessage(inc); int newMap = Maps.IndexOf(Server.MapFromID(msg.ID)); LoginMessage login = Server.Logins[inc.SenderConnection.RemoteUniqueIdentifier]; //Fetch stored login from dictionary Maps[newMap].Players.Add(new Player(Maps[newMap], Maps[newMap].Spawn, login.Username, inc.SenderConnection.RemoteUniqueIdentifier, Server.FindEmptyID(Maps[newMap])) { Tint = login.Color }); sender = Server.PlayerFromRUI(inc.SenderConnection.RemoteUniqueIdentifier, true); NetManager.Send(new InitMessage(sender.Map), sender); //Send message to player notifing he is connected and ready NetManager.Send(new PlayerJoinMessage(sender.Username, sender.ID, true, sender.Tint), sender); //Log message Log.WriteLine(LogType.Room, "{0} joined: {1}", login.Username, Maps[newMap].Name); //Send message to everyone notifying of new user NetManager.BroadcastExcept(new PlayerJoinMessage(sender.Username, sender.ID, false, sender.Tint), sender); //Let new player know of all existing players and their states (Mode, Position, Smiley) foreach (Player player in sender.Map.Players) { if (player.ID != sender.ID) { NetManager.Send(new PlayerJoinMessage(player.Username, player.ID, false, player.Tint), sender); NetManager.Send(new PlayerStateMessage(player), sender); if (player.Mode != PlayerMode.Normal) { NetManager.Send(new PlayerModeMessage(player), sender); } if (player.Smiley != SmileyType.Default) { NetManager.Send(new PlayerSmileyMessage(player, player.Smiley), sender); } } } } break; } //When a player requests to make a room case MessageTypes.CreateRoom: //If the sender isn't null, then they are already in a room { if (sender == null) { CreateRoomMessage msg = new CreateRoomMessage(inc); Map newMap = Server.CreateMap(msg.Name, msg.Description); LoginMessage login = Server.Logins[inc.SenderConnection.RemoteUniqueIdentifier]; //Fetch stored login from dictionary newMap.Players.Add(new Player(newMap, newMap.Spawn, login.Username, inc.SenderConnection.RemoteUniqueIdentifier, Server.FindEmptyID(newMap)) { Tint = login.Color }); sender = Server.PlayerFromRUI(inc.SenderConnection.RemoteUniqueIdentifier, true); //Send message to player notifing he is connected and ready NetManager.Send(new InitMessage(sender.Map), sender); NetManager.Send(new PlayerJoinMessage(sender.Username, sender.ID, true, sender.Tint), sender); //Log message Log.WriteLine(LogType.Room, "{0} created room: {1}", login.Username, newMap.Name); } break; } } }
/// <summary> /// Handles a data message (The bulk of all messages recieved, containing player movements, block places, etc) /// </summary> private void HandleDataMessage(NetIncomingMessage im) { MessageTypes messageType = (MessageTypes)im.ReadByte(); //Find the type of data message sent switch (messageType) { case MessageTypes.Lobby: //Lobby list packet { if (Game.CurrentGameState == GameState.Lobby) { LobbyScreen screen = MainWindow.ScreenManager.Current as LobbyScreen; LobbyMessage msg = new LobbyMessage(im); screen.Name = msg.ServerName; screen.Description = msg.Description; screen.Intro = msg.Intro; screen.Online = msg.Online; screen.Rooms = msg.Rooms; screen.Lobby.LoadRooms(); } break; } case MessageTypes.PlayerJoin: //Player join message { PlayerJoinMessage user = new PlayerJoinMessage(im); //Add player to map Map.Players.Add(new Player(Map, Map.Spawn, user.Username, user.ID) { Tint = user.Color }); //Add user to userlist (MainWindow.ScreenManager.Current as GameScreen).PlayerList.Items.Add(user.Username); if (user.ID != Game.MyID && recievedInit) //Broadcast join message to chat { (MainWindow.ScreenManager.Current as GameScreen).SystemChat(user.Username + " [color:LightGray]has[/color] [color:LightGreen]joined.[/color]"); } if (user.Me) { //Let game know of it's own player Game.MyID = user.ID; Game.MyIndex = (byte)Map.Players.IndexOf(Map.Players.First(x => x.ID == Game.MyID)); Game.Me.Tint = Game.MyColor; } break; } case MessageTypes.PlayerLeave: //Player leave message { PlayerLeaveMessage user = new PlayerLeaveMessage(im); //Remove player if (user.ID != Game.MyID) { Player player = (Player)Map.PlayerFromID(user.ID); Map.Players.Remove((Player)Map.PlayerFromID(user.ID)); (MainWindow.ScreenManager.Current as GameScreen).PlayerList.Items.Remove(player.Username); (MainWindow.ScreenManager.Current as GameScreen).SystemChat(player.Username + " [color:LightGray]has[/color] [color:IndianRed]left.[/color]"); //Rebuild indexes for (int i = 0; i < Map.Players.Count; i++) { Map.Players[i].Index = i; if (Map.Players[i].ID == Game.MyID) { Game.MyIndex = (byte)i; } } } break; } case MessageTypes.PlayerStatus: //Player move message { if (Game.CurrentGameState == GameState.Game) { PlayerStateMessage user = new PlayerStateMessage(im); Player player = (Player)Map.PlayerFromID(user.ID); player.SimulationState.Position = user.Position.ToVector2(); player.SimulationState.Velocity = user.Velocity.ToVector2(); player.SimulationState.Movement = user.Movement.ToVector2(); if (!recievedInit) //If we have not recieved init (meaning we are not in game yet), set the initial positions directly so interpolation doesn't mess with them { player.DisplayState.Position = player.SimulationState.Position; } player.VirtualJump = user.IsJumping; } break; } case MessageTypes.Block: //Block place message { if (Game.CurrentGameState == GameState.Game) { BlockMessage msg = new BlockMessage(im); BlockType block = BlockType.FromID(msg.BlockID); if (Map.CanPlaceBlock(msg.X, msg.Y, msg.Z, block)) { Map.Tiles[msg.X, msg.Y, msg.Z].Block = block; } } break; } case MessageTypes.PlayerSmiley: //Smiley change message { if (Game.CurrentGameState == GameState.Game) { PlayerSmileyMessage msg = new PlayerSmileyMessage(im); Player p = (Player)Map.PlayerFromID(msg.ID); p.Smiley = msg.Smiley; } break; } case MessageTypes.PlayerMode: //Player mode change message { if (Game.CurrentGameState == GameState.Game) { PlayerModeMessage mode = new PlayerModeMessage(im); Map.PlayerFromID(mode.ID).Mode = (PlayerMode)mode.Mode; } break; } case MessageTypes.Chat: //Chat message { if (Game.CurrentGameState == GameState.Game) { ChatMessage chat = new ChatMessage(im); (MainWindow.ScreenManager.Current as GameScreen).AddChat(Map.PlayerFromID(chat.ID).Username, chat.Message); } break; } case MessageTypes.Init: //Initialization message with world data { Game.Map = new Bricklayer.Client.World.Map(game, 1, 1); InitMessage msg = new InitMessage(im, Map); Game.Map.Minimap = new Minimap(Game.Map, msg.Width, msg.Height) { Position = new Microsoft.Xna.Framework.Vector2(8, 8) }; Game.Map.CreateCamera(); Game.CurrentGameState = GameState.Game; (MainWindow.ScreenManager.Current as GameScreen).Show(); (MainWindow.ScreenManager.Current as GameScreen).SystemChat("Connected to [color:LightGray]" + Game.Host + ":" + Game.Port + "[/color]"); recievedInit = true; break; } } }