/// <inheritdoc/> /// <remarks> /// <include file="DocInclude/common.xml" path="docs/item[@name='Connection_SendBytes_General']/*" /> /// <para> /// The sendOption parameter is ignored by the TcpConnection as TCP only supports FragmentedReliable /// communication, specifying anything else will have no effect. /// </para> /// </remarks> public override void SendBytes(byte[] bytes, SendOption sendOption = SendOption.FragmentedReliable) { //Get bytes for length //byte[] fullBytes = AppendLengthHeader(bytes); //TODO 追加信息是个什么鬼 //Write the bytes to the socket lock (socketLock) { if (State != ConnectionState.Connected) { throw new InvalidOperationException("Could not send data as this Connection is not connected. Did you disconnect?"); } try { socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, null, null); //TODO 异步发送不需要回调函数吗? } catch (Exception e) { HazelException he = new HazelException("Could not send data as an occured.", e); HandleDisconnect(he); throw he; } } Statistics.LogFragmentedSend(bytes.Length, bytes.Length); }
/// <summary> /// Appends the length header to the bytes. /// </summary> /// <param name="bytes">The source bytes.</param> /// <param name="sendOption">Allows for marking packet as KeepAlive. (Zero body length)</param> /// <returns>The new bytes.</returns> static byte[] AppendLengthHeader(byte[] bytes, SendOption sendOption) { byte[] fullBytes = new byte[bytes.Length + 4]; if (sendOption == SendOption.KeepAlive) { //Append length as 0 fullBytes[0] = 0; fullBytes[1] = 0; fullBytes[2] = 0; fullBytes[3] = 0; } else { //Append length fullBytes[0] = (byte)(((uint)bytes.Length >> 24) & 0xFF); fullBytes[1] = (byte)(((uint)bytes.Length >> 16) & 0xFF); fullBytes[2] = (byte)(((uint)bytes.Length >> 8) & 0xFF); fullBytes[3] = (byte)(uint)bytes.Length; } //Add rest of bytes Buffer.BlockCopy(bytes, 0, fullBytes, 4, bytes.Length); return(fullBytes); }
public void Handle(MyPlayerAdd data, IRavenNetworkConnection connection, SendOption sendOption) { var hasAppearance = data.Appearance != null; UnityEngine.Debug.Log("Player: " + data.Name + ", received from server. POS: " + data.Position + ", has appearance: " + hasAppearance); var playerHandler = moduleManager.GetModule <PlayerHandler>(); var player = new Player() { Id = data.PlayerId, IsMe = true, Name = data.Name, Position = data.Position, Appearance = data.Appearance, Attributes = data.Attributes, Professions = data.Professions, Experience = data.Experience, Level = data.Level, Health = data.Health, }; playerHandler.Add(player); playerHandler.PlayerStatsUpdate(player.Id, data.Attributes, data.Professions); playerHandler.SetPlayerInventory(player.Id, data.Coins, data.InventoryItemId, data.InventoryItemAmount); }
public static void Handle(string timestamp, string data, ParserState state) { data = data.Trim(); var match = Regexes.SendOptionRegex.Match(data); if (match.Success) { var option = match.Groups[1].Value; var suboption = match.Groups[2].Value; var target = match.Groups[3].Value; var position = match.Groups[4].Value; var sendOption = new SendOption { OptionIndex = int.Parse(option), Position = int.Parse(position), SubOption = int.Parse(suboption), Target = int.Parse(target) }; if (state.Node.Type == typeof(Game)) { ((Game)state.Node.Object).Data.Add(sendOption); } else { throw new Exception("Invalid node " + state.Node.Type + " -- " + data); } } }
/// <summary> /// Helper method to invoke the data received event. /// </summary> /// <param name="sendOption">The send option the message was received with.</param> /// <param name="buffer">The buffer received.</param> /// <param name="dataOffset">The offset of data in the buffer.</param> void InvokeDataReceived(SendOption sendOption, byte[] buffer, int dataOffset) { byte[] dataBytes = new byte[buffer.Length - dataOffset]; Buffer.BlockCopy(buffer, dataOffset, dataBytes, 0, dataBytes.Length); InvokeDataReceived(dataBytes, sendOption); }
private bool Acknowledge( SocketService socketService, SendOption sendOption, PacketHead packetHead, IWriteStream writeStream = null) { if (socketService == null) { Logger.Error($"{nameof(socketService)} 为 null !"); return(false); } var fragment = writeStream?.ToByteFragment(); packetHead.Length = fragment.HasValue ? (ushort)(PacketHead.GetSize() + fragment?.Count) : (ushort)PacketHead.GetSize(); packetHead.SendOption = sendOption; var ws = PoolAllocator <IWriteStream> .GetObject(); if (writeStream != null) { ws.ShiftRight(writeStream.ToByteFragment()); } Packet.ToBytes(packetHead, ws); var byteSegment = ws.ToByteFragment(); var result = StartWrite(socketService, byteSegment.Buffer, byteSegment.Offset, byteSegment.Count, ws, true); SocketStatistics.LogUnreliableSend(); SocketStatistics.LogTotalBytesSent(packetHead.Length); return(true); }
public void Handle(PlayerInventory data, IRavenNetworkConnection connection, SendOption sendOption) { UnityEngine.Debug.Log("Player Inventory Updated"); var playerHandler = moduleManager.GetModule <PlayerHandler>(); playerHandler.SetPlayerInventory(data.PlayerId, data.Coins, data.ItemId, data.Amount); }
public void Handle(PlayerItemAdd data, IRavenNetworkConnection connection, SendOption sendOption) { UnityEngine.Debug.Log("Add item to player (id: " + data.PlayerId + "), itemId: " + data.ItemId + ", amount: " + data.Amount); var playerHandler = moduleManager.GetModule <PlayerHandler>(); playerHandler.PlayerItemAdd(data.PlayerId, data.ItemId, data.Amount); }
private int InternalExecute() { if (SendOption.HasValue() && ReceiveOption.HasValue()) { Console.WriteLine("Use either -s or -r option."); return(ExitCodes.SendAndReceiveSpecified); } var isSend = !ReceiveOption.HasValue(); var file = FileArgument.Value; if (isSend && string.IsNullOrEmpty(file)) { Console.WriteLine("No file specified."); return(ExitCodes.NoFileSpecified); } if (!string.IsNullOrEmpty(file) && !CheckFile(file)) { return(ExitCodes.InvalidFileSpecified); } ushort port = 56657; if (PortOption.HasValue()) { var canPortParse = PortOption.HasValue() && ushort.TryParse(PortOption.Value(), out port); if (!canPortParse) { Console.WriteLine("Invalid port."); return(ExitCodes.InvalidPort); } } var bufferSize = 65536 * 32; if (BufferOption.HasValue()) { var canBufferParse = BufferOption.HasValue() && int.TryParse(BufferOption.Value(), out bufferSize); if (!canBufferParse) { Console.WriteLine("Invalid Buffer Size."); return(ExitCodes.InvalidBufferSize); } } bool AcceptFileCallback(string name, long size, string sender, IPAddress source) { Console.Write($"File {name} ({Progress.ToFileSize(size)}) announced by {sender} ({source}), accept? (y/n) "); var read = Console.ReadLine(); return(read == "y"); } var worker = isSend ? (Worker) new SendWorker(port, bufferSize, file) : new ReceiveWorker(port, bufferSize, file, AcceptFileCallback); return(worker.Run()); }
public void SendBytes(PacketType type, byte[] data, SendOption sendOption = SendOption.None) { byte[] buffer = new byte[data.Length + 1]; buffer[0] = (byte)type; Array.Copy(data, 0, buffer, 1, data.Length); Connection.SendBytes(buffer, sendOption); }
/// /// <param name="sendOption">The option specifying how the message should be sent.</param> public static MessageWriter Get(SendOption sendOption = SendOption.None) { var output = WriterPool.GetObject(); output.Clear(sendOption); return(output); }
public void Send <T>(Connection connection, short packetId, T packet, SendOption sendOption) { connection.SendBytes(packetSerializer.Serialize(new NetworkPacket() { Id = packetId, Data = packet }), sendOption); }
/// <summary> /// Helper method to invoke the data received event. /// </summary> /// <param name="sendOption">The send option the message was received with.</param> /// <param name="buffer">The buffer received.</param> /// <param name="dataOffset">The offset of data in the buffer.</param> void InvokeDataReceived(SendOption sendOption, MessageReader buffer, int dataOffset, int bytesReceived) { buffer.Offset = dataOffset; buffer.Length = bytesReceived - dataOffset; buffer.Position = 0; InvokeDataReceived(buffer, sendOption); }
public void Handle(UserPlayerList data, IRavenNetworkConnection connection, SendOption sendOption) { var players = data.GetPlayers(); UnityEngine.Debug.Log("UserPlayerList - (Player Count:" + players.Length + "), received from server."); var loginHandler = this.moduleManager.GetModule <CharacterHandler>(); loginHandler.SetCharacterList(players); }
public void Handle(AuthResponse data, IRavenNetworkConnection connection, SendOption sendOption) { //logger.Debug("Login response: " + data.Status); var auth = moduleManager.GetModule <Authentication>(); if (auth != null) { auth.SetResult(data.Status); } }
public void Handle(PlayerRemove data, IRavenNetworkConnection connection, SendOption sendOption) { logger.Debug("Player Remove, player id: " + data.PlayerId); var playerHandler = moduleManager.GetModule <PlayerHandler>(); var player = new Player() { Id = data.PlayerId }; playerHandler.Remove(player); }
public void Handle(ObjectRemove data, IRavenNetworkConnection connection, SendOption sendOption) { logger.Debug("Remove Instance Id: " + data.ObjectServerId + " received from server."); var objectHandler = moduleManager.GetModule <ObjectHandler>(); var obj = new SceneObject() { Id = data.ObjectServerId }; objectHandler.Remove(obj); }
/// <summary> /// Called when data has been received by the socket. /// </summary> /// <param name="result">The asyncronous operation's result.</param> void ReadCallback(IAsyncResult result) { int bytesReceived; //End the receive operation try { lock (socketLock) bytesReceived = socket.EndReceive(result); } catch (ObjectDisposedException) { //If the socket's been disposed then we can just end there. return; } catch (SocketException e) { HandleDisconnect(new HazelException("A socket exception occured while reading data.", e)); return; } //Exit if no bytes read, we've failed. if (bytesReceived == 0) { HandleDisconnect(); return; } //Decode the data received byte[] buffer = HandleReceive(dataBuffer, bytesReceived); SendOption sendOption = (SendOption)dataBuffer[0]; //TODO may get better performance with Handle receive after and block copy call added //Begin receiving again try { StartListeningForData(); } catch (SocketException e) { HandleDisconnect(new HazelException("A Socket exception occured while initiating a receive operation.", e)); } catch (ObjectDisposedException) { //If the socket's been disposed then we can just end there. return; } if (buffer != null) { InvokeDataReceived(buffer, sendOption); } }
/// <inheritdoc/> /// <remarks> /// <include file="DocInclude/common.xml" path="docs/item[@name='Connection_SendBytes_General']/*" /> /// <para> /// Udp connections can currently send messages using <see cref="SendOption.None"/> and /// <see cref="SendOption.Reliable"/>. Fragmented messages are not currently supported and will default to /// <see cref="SendOption.None"/> until implemented. /// </para> /// </remarks> public override void SendBytes(byte[] bytes, SendOption sendOption = SendOption.None) { //Early check if (State != ConnectionState.Connected) { throw new InvalidOperationException("Could not send data as this Connection is not connected. Did you disconnect?"); } //Add header information and send HandleSend(bytes, (byte)sendOption); }
/// <summary> /// Invokes the DataReceived event. /// </summary> /// <param name="msg">The bytes received.</param> /// <param name="sendOption">The <see cref="SendOption"/> the message was received with.</param> /// <remarks> /// Invokes the <see cref="DataReceived"/> event on this connection to alert subscribers a new message has been /// received. The bytes and the send option that the message was sent with should be passed in to give to the /// subscribers. /// </remarks> protected void InvokeDataReceived(MessageReader msg, SendOption sendOption) { //Make a copy to avoid race condition between null check and invocation Action <DataReceivedEventArgs> handler = DataReceived; if (handler != null) { handler(new DataReceivedEventArgs(msg, sendOption)); } //msg.Recycle(); }
public void Handle(ObjectAdd data, IRavenNetworkConnection connection, SendOption sendOption) { logger.Debug("Add Instance Id: " + data.ObjectServerId + ", Object Id: " + data.ObjectId + " received from server."); var objectHandler = moduleManager.GetModule <ObjectHandler>(); var obj = new SceneObject() { Id = data.ObjectServerId, Type = data.ObjectId, Position = data.Position, }; objectHandler.Add(obj); }
/// <summary> /// Invokes the DataReceived event. /// </summary> /// <param name="bytes">The bytes received.</param> /// <param name="sendOption">The <see cref="SendOption"/> the message was received with.</param> /// <remarks> /// Invokes the <see cref="DataReceived"/> event on this connection to alert subscribers a new message has been /// received. The bytes and the send option that the message was sent with should be passed in to give to the /// subscribers. /// </remarks> protected void InvokeDataReceived(byte[] bytes, SendOption sendOption) { DataReceivedEventArgs args = DataReceivedEventArgs.GetObject(); args.Set(bytes, sendOption); //Make a copy to avoid race condition between null check and invocation EventHandler <DataReceivedEventArgs> handler = DataReceived; if (handler != null) { handler(this, args); } }
public void Send <T>(Connection connection, T packet, SendOption sendOption) { if (!packetRegistry.TryGetId(typeof(T), out var id)) { Register <T>(); } if (packetRegistry.TryGetId(typeof(T), out id)) { Send(connection, id, packet, sendOption); return; } throw new Exception("Unable to send packet. Failed to lookup packetid for type " + typeof(T).FullName); }
public void Clear(SendOption sendOption) { this.messageStarts.Clear(); this.SendOption = sendOption; this.Buffer[0] = (byte)sendOption; switch (sendOption) { case SendOption.None: this.Length = this.Position = 1; break; case SendOption.Reliable: this.Length = this.Position = 3; break; } }
public void Handle(PlayerAdd data, IRavenNetworkConnection connection, SendOption sendOption) { UnityEngine.Debug.Log("Player: " + data.Name + ", received from server."); var playerHandler = moduleManager.GetModule <PlayerHandler>(); var player = new Player() { Id = data.PlayerId, IsMe = false, Name = data.Name, Position = data.Position, Destination = data.Destination, Appearance = data.Appearance }; playerHandler.Add(player); }
public void Handle(MyPlayerAdd data, IRavenNetworkConnection connection, SendOption sendOption) { //UnityEngine.Debug.Log("Player: " + data.Name + ", received from server. POS: " + data.Position); //var playerHandler = moduleManager.GetModule<PlayerHandler>(); //var player = new Player() //{ // Id = data.PlayerId, // IsMe = true, // Name = data.Name, // Position = data.Position, //}; //playerHandler.Add(player); //playerHandler.PlayerStatsUpdate(player.Id, data.Experience, data.EffectiveLevel); }
public void Handle(NpcAdd data, IRavenNetworkConnection connection, SendOption sendOption) { logger.Debug("Add Instance Id: " + data.NpcId + ", Npc Id: " + data.ServerId + " received from server."); var npcHandler = moduleManager.GetModule <NpcHandler>(); var npc = new Npc() { NpcId = data.NpcId, Id = data.ServerId, Position = data.Position, Destination = data.Destination, Rotation = data.Rotation, Attributes = data.Attributes, Endurance = data.Endurance, Health = data.Health, Level = data.Level }; npcHandler.Add(npc); }
/// <summary> /// 发送数据 /// </summary> private bool Write(SocketService socketService, ulong messageId, SendOption sendOption) { using (var writeStream = PoolAllocator <IWriteStream> .GetObject()) { var packetHead = new PacketHead { Length = (ushort)PacketHead.GetSize(), PacketId = messageId, SendOption = sendOption, TotalBytes = 0, FragmentId = 0, TotalFragments = 1 }; Packet.ToBytes(packetHead, writeStream); var byteFragment = writeStream.ToByteFragment(); var result = _writer.Client.SendTo(byteFragment.Buffer, byteFragment.Offset, byteFragment.Count, SocketFlags.None, socketService.Connection.RemoteAddress); socketService.OnWrite(result == byteFragment.Count); return(result == byteFragment.Count); } }
public void Handle(IRavenNetworkConnection connection, NetworkPacket packet, SendOption sendOption) { if (packet.Data == null) { return; } var key = packet.Data.GetType().Name; if (packetHandlers.TryGetValue(key, out var handler)) { packetHandlerMethod[key].Invoke(handler.Value, new object[] { packet.Data, connection, sendOption }); return; } lock (filterMutex) { var filter = filters.FirstOrDefault(x => x.CanApply(packet.Data.GetType())); if (filter != null && filter.Apply(packet.Data)) { filters.Remove(filter); } } }
protected override bool WriteMessage( SocketService socketService, SendOption sendOption, ulong messageId, IWriteStream writeStream) { if (socketService == null) { Logger.Error($"{nameof(socketService)} 为 null !"); return(false); } var fragment = writeStream?.ToByteFragment(); var packetHead = new PacketHead { Length = fragment.HasValue ? (ushort)(PacketHead.GetSize() + fragment?.Count) : (ushort)PacketHead.GetSize(), PacketId = messageId, SendOption = sendOption, TotalBytes = fragment.HasValue ? (ushort)fragment?.Count : (ushort)0, FragmentId = 0, TotalFragments = 1 }; var ws = PoolAllocator <IWriteStream> .GetObject(); if (fragment.HasValue) { ws.ShiftRight((ByteFragment)fragment); } Packet.ToBytes(packetHead, ws); var byteSegment = ws.ToByteFragment(); var result = StartWrite(socketService, byteSegment.Buffer, byteSegment.Offset, byteSegment.Count, ws, true); SocketStatistics.LogUnreliableSend(); SocketStatistics.LogTotalBytesSent(packetHead.Length); return(result); }