// 수신된 데이터가 어느 데이터 구조에 적합한지 판단후 등록된 함수 호출 public void ReceivePacket(byte[] data) { PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); // 패킷 추출 // 맨앞자리만 추출 serializer.Deserialize(data, ref header); // int packetId = (int)header.packetId; int headerSize = sizeof(int); byte[] packetData = new byte[data.Length - headerSize]; Buffer.BlockCopy(data, headerSize, packetData, 0, packetData.Length); // 예외처리 if (packetId >= 18 || packetId <= 0 || !notifier.ContainsKey(packetId)) { return; } Debug.Log((cnt++) + " 수신한 패킷 ID : " + packetId + " " + (PacketId)packetId + " " + Time.time); // 등록된 적절한 receive함수 호출 notifier[packetId]((PacketId)packetId, packetData); }
// 데이터를 서버로 전송(UDP) public int SendUnreliable <T>(IPacket <T> packet) { int sendSize = 0; if (transportUDP != null) { // 헤더 정보 생성 PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); // FIX THIS : 명시적 형변환 해줌. 소스코드와 다름 header.packetId = (int)packet.GetPacketId(); byte[] headerData = null; if (serializer.Serialize(header) == true) { headerData = serializer.GetSerializedData(); } byte[] packetData = packet.GetData(); byte[] data = new byte[headerData.Length + packetData.Length]; int headerSize = Marshal.SizeOf(typeof(PacketHeader)); Buffer.BlockCopy(headerData, 0, data, 0, headerSize); Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length); sendSize = transportUDP.Send(data, data.Length); } return(sendSize); }
//데이타를 전송하는 메소드. byte[] msg 를 newIPEndPoint로 전송한다. public void DataSend() { if (sendMsgs.Count > 0) { DataPacket packet; lock (sendLock) { packet = sendMsgs.Dequeue(); } Debug.Log("메시지 보냄 : " + packet.endPoint); Debug.Log("메시지 보냄 (길이) : " + packet.headerData.length); Debug.Log("메시지 보냄 (출처) : " + packet.headerData.source); Debug.Log("메시지 보냄 (타입) : " + packet.headerData.id); HeaderSerializer headerSerializer = new HeaderSerializer(); headerSerializer.Serialize(packet.headerData); byte[] header = headerSerializer.GetSerializedData(); byte[] msg = CombineByte(header, packet.msg); if (packet.headerData.source == (byte)DataHandler.Source.ClientSource) { udpSock.BeginSendTo(msg, 0, msg.Length, SocketFlags.None, packet.endPoint, new AsyncCallback(SendData), null); } else if (packet.headerData.source == (byte)DataHandler.Source.ServerSource) { tcpSock.Send(msg, 0, msg.Length, SocketFlags.None); } } }
// 데이터를 서버로 전송(TCP) public int SendReliable <T>(IPacket <T> packet) { int sendSize = 0; if (transportTCP != null) { // 모듈에서 사용할 헤더 정보를 생성합니다. PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); //packetid = skill, moving 등등 moving은 2 header.packetId = (int)packet.GetPacketId(); byte[] headerData = null; if (serializer.Serialize(header) == true) { headerData = serializer.GetSerializedData(); } byte[] packetData = packet.GetData(); //움직임 정보 들은 데이터 byte[] data = new byte[headerData.Length + packetData.Length]; int headerSize = Marshal.SizeOf(typeof(PacketHeader)); Buffer.BlockCopy(headerData, 0, data, 0, headerSize); Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length); string str = "Send reliable packet[" + header.packetId + "]"; sendSize = transportTCP.Send(data, data.Length); } return(sendSize); }
private byte[] CreatePacket <T>(IPacket <T> packet) // 패킷 만드는 메서드 { byte[] packetData = packet.GetPacketData(); // 패킷의 데이터를 바이트화 // 헤더 생성 PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); header.length = (short)packetData.Length; // 패킷 데이터의 길이를 헤더에 입력 header.id = (byte)packet.GetPacketId(); // 패킷 데이터에서 ID를 가져와 헤더에 입력 //Debug.Log("패킷 전송 - id : " + header.id.ToString() + " length :" + header.length); byte[] headerData = null; if (serializer.Serialize(header) == false) { return(null); } headerData = serializer.GetSerializedData(); // 헤더 데이터를 패킷 바이트로 변환 byte[] data = new byte[headerData.Length + header.length]; // 최종 패킷의 길이 = 헤더패킷길이+내용패킷길이 // 헤더와 내용을 하나의 배열로 복사 int headerSize = Marshal.SizeOf(header.id) + Marshal.SizeOf(header.length); Buffer.BlockCopy(headerData, 0, data, 0, headerSize); Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length); return(data); }
// private method // create packet include header private byte[] CreatePacketStream <T, U>(Packet <T, U> packet) { // data iniialize byte[] packetData = packet.GetPacketData(); PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); // set header data header.length = (short)packetData.Length; header.id = (byte)packet.GetPacketID(); byte[] headerData = null; try { serializer.Serialize(header); } catch { } headerData = serializer.GetSerializeData(); // header / packet data combine byte[] data = new byte[headerData.Length + packetData.Length]; int headerSize = Marshal.SizeOf(header.id) + Marshal.SizeOf(header.length); Buffer.BlockCopy(headerData, 0, data, 0, headerSize); Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length); return(data); }
private void Receive(int node, byte[] data) { PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); serializer.SetDeserializedData(data); bool ret = serializer.Deserialize(ref header); if (ret == false) { Debug.Log("Invalid header data."); // 패킷으로서 인식할 수 없으므로 폐기합니다. return; } string str = ""; for (int i = 0; i < 16; ++i) { str += data[i] + ":"; } Debug.Log(str); int packetId = (int)header.packetId; if (packetId < m_notifier.Count && m_notifier[packetId] != null) { int headerSize = Marshal.SizeOf(typeof(PacketHeader)); byte[] packetData = new byte[data.Length - headerSize]; Buffer.BlockCopy(data, headerSize, packetData, 0, packetData.Length); m_notifier[packetId](node, packetData); } }
public Task Dispatch(TransportOperations outgoingMessages, TransportTransaction transaction, ContextBag context) { foreach (var operation in outgoingMessages.UnicastTransportOperations) { var basePath = BaseDirectoryBuilder.BuildBasePath(operation.Destination); var nativeMessageId = Guid.NewGuid().ToString(); var bodyPath = Path.Combine(basePath, ".bodies", $"{nativeMessageId}.xml"); var dir = Path.GetDirectoryName(bodyPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllBytes(bodyPath, operation.Message.Body); var messageContents = new List <string> { bodyPath, HeaderSerializer.Serialize(operation.Message.Headers) }; var messagePath = Path.Combine(basePath, $"{nativeMessageId}.txt"); // write to temp file first so an atomic move can be done // this avoids the file being locked when the receiver tries to process it var tempFile = Path.GetTempFileName(); File.WriteAllLines(tempFile, messageContents); File.Move(tempFile, messagePath); } return(TaskEx.CompletedTask); }
// private method // packet seperater -> header / packet data private bool SeperatePacket(byte[] originalData, out int packetID, out byte[] seperatedData) { PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); serializer.SetDeserializedData(originalData); serializer.Deserialize(ref header); int headerSize = Marshal.SizeOf(header.id) + Marshal.SizeOf(header.length); int packetDataSize = originalData.Length - headerSize; byte[] packetData = null; if (packetDataSize > 0) { packetData = new byte[packetDataSize]; Buffer.BlockCopy(originalData, headerSize, packetData, 0, packetData.Length); } else { packetID = header.id; seperatedData = null; return(false); } packetID = header.id; seperatedData = packetData; return(true); }
public void Can_round_trip_headers() { if (Environment.OSVersion.Platform != PlatformID.Win32NT) { Assert.Ignore("ApprovalTests only works on Windows"); } var input = new Dictionary <string, string> { { "key 1", "value 1" }, { "key 2", "value 2" } }; var serialized = HeaderSerializer.Serialize(input); TestApprover.Verify(serialized); var deserialize = HeaderSerializer.Deserialize(serialized); CollectionAssert.AreEquivalent(input, deserialize); }
public int SendUnreliable <T>(IPacket <T> packet) { int sendSize = 0; if (m_udp != null) { // 모듈에서 사용할 헤더 정보를 생성합니다. PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); header.packetId = packet.GetPacketId(); byte[] headerData = null; if (serializer.Serialize(header) == true) { headerData = serializer.GetSerializedData(); } byte[] packetData = packet.GetData(); byte[] data = new byte[headerData.Length + packetData.Length]; int headerSize = Marshal.SizeOf(typeof(PacketHeader)); Buffer.BlockCopy(headerData, 0, data, 0, headerSize); Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length); sendSize = m_udp.Send(data, data.Length); } return(sendSize); }
public void SendReliableToAll(PacketId id, byte[] data) { if (m_tcp != null) { // 모듈에서 사용할 헤더 정보를 생성합니다. PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); header.packetId = id; byte[] headerData = null; if (serializer.Serialize(header) == true) { headerData = serializer.GetSerializedData(); } byte[] pdata = new byte[headerData.Length + data.Length]; int headerSize = Marshal.SizeOf(typeof(PacketHeader)); Buffer.BlockCopy(headerData, 0, pdata, 0, headerSize); Buffer.BlockCopy(data, 0, pdata, headerSize, data.Length); string str = "Send reliable packet[" + header.packetId + "]"; int sendSize = m_tcp.Send(pdata, pdata.Length); if (sendSize < 0) { // 송신 오류. } } }
public int Send(PacketId id, byte[] data) { int sendSize = 0; if (m_tcp != null) { // 모듈에서 사용할 헤더 정보를 생성합니다. PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); header.packetId = id; byte[] headerData = null; if (serializer.Serialize(header) == true) { headerData = serializer.GetSerializedData(); } byte[] packetData = new byte[headerData.Length + data.Length]; int headerSize = Marshal.SizeOf(typeof(PacketHeader)); Buffer.BlockCopy(headerData, 0, packetData, 0, headerSize); Buffer.BlockCopy(data, 0, packetData, headerSize, data.Length); sendSize = m_tcp.Send(data, data.Length); } return(sendSize); }
public void ReceivePacket(byte[] data) { PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); bool ret = serializer.Deserialize(data, ref header); if (ret == false) { // 패킷으로서 인식할 수 없으므로 폐기합니다. return; } int packetId = (int)header.packetId; if (m_notifier.ContainsKey(packetId) && m_notifier[packetId] != null) { int headerSize = Marshal.SizeOf(typeof(PacketHeader));//sizeof(PacketId) + sizeof(int); byte[] packetData = new byte[data.Length - headerSize]; Buffer.BlockCopy(data, headerSize, packetData, 0, packetData.Length); m_notifier[packetId]((PacketId)packetId, packetData); } }
public int Send <T>(int node, PacketId id, IPacket <T> packet) { int sendSize = 0; if (m_sessionTcp != null) { // 모듈에서 사용하는 헤더 정보 생성. PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); header.packetId = id; byte[] headerData = null; if (serializer.Serialize(header) == true) { headerData = serializer.GetSerializedData(); } byte[] packetData = packet.GetData(); byte[] data = new byte[headerData.Length + packetData.Length]; int headerSize = Marshal.SizeOf(typeof(PacketHeader)); Buffer.BlockCopy(headerData, 0, data, 0, headerSize); Buffer.BlockCopy(packetData, 0, data, headerSize, packetData.Length); //string str = "Send Packet[" + id + "]"; sendSize = m_sessionTcp.Send(node, data, data.Length); } return(sendSize); }
public Task Dispatch(TransportOperations outgoingMessages, TransportTransaction transaction, ContextBag context) { foreach (var operation in outgoingMessages.UnicastTransportOperations) { var serializedHeaders = HeaderSerializer.Serialize(operation.Message.Headers); var transportSettings = _settings.getTransportSettings(); var queueIndex = operation.Destination.IndexOf("@", StringComparison.Ordinal); string to; string subject; if (queueIndex > 0) { to = operation.Destination.Substring(queueIndex + 1); subject = $"NSB-MSG-{operation.Destination.Substring(0, queueIndex)}-{operation.Message.MessageId}"; } else { to = transportSettings.ImapUser; subject = $"NSB-MSG-{operation.Destination}-{operation.Message.MessageId}"; } SmtpUtils.SendMail( transportSettings.SmtpServer, transportSettings.SmtpServerPort, transportSettings.SmtpUser, transportSettings.SmtpPassword, transportSettings.ImapUser, to, subject, serializedHeaders, operation.Message.Body); } return(Task.CompletedTask); }
private void Receive(int node, byte[] data) { PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); serializer.SetDeserializedData(data); bool ret = serializer.Deserialize(ref header); if (ret == false) { Debug.Log("Invalid header data."); // 패킷으로서 인식할 수 없으므로 폐기한다. return; } int packetId = (int)header.packetId; if (m_notifier.ContainsKey(packetId) && m_notifier[packetId] != null) { int headerSize = Marshal.SizeOf(typeof(PacketHeader)); byte[] packetData = new byte[data.Length - headerSize]; Buffer.BlockCopy(data, headerSize, packetData, 0, packetData.Length); m_notifier[packetId](node, header.packetId, packetData); } }
public IImageDecoder BuildDecoder(Stream imageReaderStream, DecodingConfiguration decodingConfiguration) { Header header; try { header = new HeaderSerializer(Signature.Bytes.Length).DeserializeAsync(imageReaderStream).Result; } catch (Exception) { throw new InvalidHeaderException("Could not read file header"); } if (!header.Signature.SequenceEqual(Signature.Bytes)) { throw new InvalidHeaderException("Incorrect file signature"); } if (!Enum.IsDefined(typeof(Version), header.Version)) { throw new UnsupportedVersionException(String.Format("File with version {0} is not supported", header.Version)); } switch ((Version)header.Version) { case Version.V1: return(new V1.ImageDecoder(decodingConfiguration)); case Version.V2: return(new V2.ImageDecoder(decodingConfiguration)); default: throw new UnsupportedVersionException(String.Format("File with version {0} is not supported", header.Version)); } }
static async Task <List <SagaDataSnapshot> > LoadStoredCopies(DbConnectionProvider connectionProvider, string tableName) { var storedCopies = new List <SagaDataSnapshot>(); using (var connection = await connectionProvider.GetConnection()) { using (var command = connection.CreateCommand()) { command.CommandText = $@"SELECT * FROM [{tableName}]"; using var reader = command.ExecuteReader(); while (await reader.ReadAsync()) { var sagaData = (ISagaData) new ObjectSerializer().DeserializeFromString((string)reader["data"]); var metadata = new HeaderSerializer().DeserializeFromString((string)reader["metadata"]); storedCopies.Add(new SagaDataSnapshot { SagaData = sagaData, Metadata = metadata }); } } await connection.Complete(); } return(storedCopies); }
private bool getPacketContent(byte[] data, out int id, out byte[] outContent) { PacketHeader header = new PacketHeader(); HeaderSerializer serializer = new HeaderSerializer(); serializer.SetDeserializedData(data); serializer.Deserialize(ref header); int headerSize = 3; // 헤더사이즈 short + byte = 3 int packetContentSize = data.Length - headerSize; byte[] packetContent = null; if (packetContentSize > 0) //헤더만 있는 패킷을 대비해서 예외처리, 데이터가 있는 패킷만 데이터를 만든다 { packetContent = new byte[packetContentSize]; Buffer.BlockCopy(data, headerSize, packetContent, 0, packetContent.Length); } else { id = header.id; outContent = null; return(false); } //Debug.Log("받은 패킷 - id : " + header.id + " dataLength : " + packetData.Length); id = header.id; outContent = packetContent; return(true); }
/// <summary> /// Converts a msmq message <see cref="Message"/> into an NServiceBus TransportMessage. /// </summary> /// <param name="message">The MSMQ message to convert.</param> /// <returns>An NServiceBus message.</returns> public TransportMessage ConvertToTransportMessage(Message message) { TransportMessage result = new TransportMessage(); result.Id = message.Id; result.CorrelationId = (message.CorrelationId == "00000000-0000-0000-0000-000000000000\\0" ? null : message.CorrelationId); result.Recoverable = message.Recoverable; result.TimeToBeReceived = message.TimeToBeReceived; result.ReturnAddress = GetIndependentAddressForQueue(message.ResponseQueue); FillIdForCorrelationAndWindowsIdentity(result, message); if (result.IdForCorrelation == null || result.IdForCorrelation == string.Empty) { result.IdForCorrelation = result.Id; } if (message.Extension != null) { if (message.Extension.Length > 0) { MemoryStream stream = new MemoryStream(message.Extension); object o = HeaderSerializer.Deserialize(stream); result.Headers = o as List <HeaderInfo>; } } return(result); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); HeaderSerializer.CallSerializer(); Console.ReadKey(); }
public void DataHandle() { if (receiveMsgs.Count != 0) { //패킷을 Dequeue 한다 패킷 : 메시지 타입 + 메시지 내용 tcpPacket = receiveMsgs.Dequeue(); //타입과 내용을 분리한다 msgType = tcpPacket.msg [0]; msg = new byte[tcpPacket.msg.Length - 1]; Array.Copy(tcpPacket.msg, 1, msg, 0, msg.Length); //Dictionary에 등록된 델리게이트형 메소드에서 msg를 반환받는다. RecvNotifier recvNotifier; HeaderSerializer serializer = new HeaderSerializer(); HeaderData headerData = new HeaderData(); if (m_notifier.TryGetValue(msgType, out recvNotifier)) { //send 할 id를 반환받음 headerData.id = (byte)recvNotifier(msg); } else { Console.WriteLine("DataHandler::TryGetValue 에러" + msgType); headerData.id = (byte)ServerPacketId.None; } //상대방에게서 게임종료 패캣이 왔을 때는 따로 Send하지 않기 위해서 if (headerData.id == (byte)ServerPacketId.None) { return; } //send할 메시지의 길이를 받음 headerData.length = (short)msg.Length; //헤더 serialize try { serializer.Serialize(headerData); header = serializer.GetSerializedData(); } catch { Console.WriteLine("DataHandler::HeaderSerialize 에러"); } //헤더와 메시지 내용을 합쳐서 Send paket = CombineByte(header, msg); tcpPacket = new TcpPacket(paket, tcpPacket.client); lock (sendLock) { sendMsgs.Enqueue(tcpPacket); } } }
public void HeaderSerializer_Deserialize_BadEnd_Throws() { const string header = "A.000168.68e999ca-a651-40f4-ad8f-3aaf781862b4.z\n"; var bytes = Encoding.ASCII.GetBytes(header); Assert.Throws <InvalidDataException>(() => { HeaderSerializer.Deserialize(bytes, 0, bytes.Length); }); }
public void HeaderSerializer_Deserialize_BadId_Throws() { var header = "A.000168.68e9p9ca-a651-40f4-ad8f-3aaf781862b4.1\n"; var bytes = Encoding.ASCII.GetBytes(header); Assert.ThrowsException <InvalidDataException>(() => { var result = HeaderSerializer.Deserialize(bytes, 0, bytes.Length); }); }
public void HeaderSerializer_Deserialize_LengthTooShort_Throws() { var header = "A.000168.68e999ca-a651-40f4-ad8f-3aaf781862b4.1\n"; var bytes = Encoding.ASCII.GetBytes(header); Assert.ThrowsException <ArgumentException>(() => { var result = HeaderSerializer.Deserialize(bytes, 0, 5); }); }
public void HeaderSerializer_DeserializeUnknownType() { const string header = "Z.000168.68e999ca-a651-40f4-ad8f-3aaf781862b4.1\n"; var bytes = Encoding.ASCII.GetBytes(header); var result = HeaderSerializer.Deserialize(bytes, 0, bytes.Length); Assert.Equal('Z', result.Type); Assert.Equal(168, result.PayloadLength); }
public void HeaderSerializer_Deserialize_LengthTooLong_Throws() { const string header = "A.000168.68e999ca-a651-40f4-ad8f-3aaf781862b4.1\n"; var bytes = Encoding.ASCII.GetBytes(header); Assert.Throws <ArgumentException>(() => { HeaderSerializer.Deserialize(bytes, 0, 55); }); }
public IEnumerator DataHandle() { while (true) { yield return(new WaitForSeconds(0.016f)); int readCount = receiveMsgs.Count; for (int i = 0; i < readCount; i++) { //패킷을 Dequeue 한다 //패킷 : 메시지 타입 + 메시지 내용 DataPacket packet; //lock (receiveLock) //{ packet = receiveMsgs.Dequeue(); //} HeaderData headerData = new HeaderData(); HeaderSerializer headerSerializer = new HeaderSerializer(); headerSerializer.SetDeserializedData(packet.msg); if (packet.endPoint == null) { headerSerializer.Deserialize(ref headerData); DataReceiver.ResizeByteArray(0, NetworkManager.packetSource + NetworkManager.packetId, ref packet.msg); if (server_notifier.TryGetValue(headerData.id, out serverRecvNotifier)) { serverRecvNotifier(packet); } else { Debug.Log("DataHandler::Server.TryGetValue 에러 " + headerData.id); } } else { headerSerializer.UdpDeserialize(ref headerData); DataReceiver.ResizeByteArray(0, NetworkManager.packetSource + NetworkManager.packetId + NetworkManager.udpId, ref packet.msg); if (p2p_notifier.TryGetValue(headerData.id, out p2pRecvNotifier)) { p2pRecvNotifier(packet, headerData.udpId); } else { Debug.Log("DataHandler::P2P.TryGetValue 에러 " + headerData.id); } } } } }
//패킷의 헤더 부분을 생성하는 메소드 HeaderData CreateHeader(short msgSize, P2PPacketId id) { HeaderData headerData = new HeaderData(); HeaderSerializer headerSerializer = new HeaderSerializer(); headerData.id = (byte)id; headerData.source = (byte)DataHandler.Source.ClientSource; headerData.length = (short)msgSize; return(headerData); }