public bool Decode(OnPacket onPacket, OnFrame onFrame) { int ret = ffmpeg.av_read_frame(formatContext, packet); if (ret < 0) { return(false); } onPacket?.Invoke(packet); ret = ffmpeg.avcodec_send_packet(context, packet); if (ret < 0) { return(true); } while (ret >= 0) { ret = ffmpeg.avcodec_receive_frame(context, frame); if ((ret == ffmpeg.AVERROR(ffmpeg.EAGAIN)) || (ret == ffmpeg.AVERROR_EOF)) { return(true); } else if (ret < 0) { throw new Exception("error during encoding"); } Console.WriteLine($"id: {context->frame_number}"); onFrame?.Invoke(frame); } return(true); }
private async Task Loop() { var dispatchQueue = new DispatchQueue <UdpReceiveResult>((result) => { var buffer = DataBuffer.Wrap(result.Buffer); var header = RtpPacketHeader.ReadFrom(buffer); try { OnPacket?.Invoke(new RtpPacket(buffer.Subset(header.CalculateHeaderLength()), header.SequenceNumber, header.Timestamp, header.Marker) { PayloadType = header.PayloadType, SynchronizationSource = header.SynchronizationSource }); } catch (Exception ex) { Console.Error.WriteLine($"Unexpected exception raising packet. {ex}"); } }); while (_LoopActive) { try { dispatchQueue.Enqueue(await _Server.ReceiveAsync()); } catch (ObjectDisposedException) { break; } } dispatchQueue.WaitForDrain(); dispatchQueue.Destroy(); }
private void ManipulateBuffer() { //Do we still want to handle a packet in the buffer //even if the client has already disconnected? while (m_offset >= 4 && Disposed == false) { int size = MapleAes.GetLength(m_buffer); if (size <= 0) { Dispose(); return; } if (m_offset < size + 4) { break; } var packetBuffer = new byte[size]; Buffer.BlockCopy(m_buffer, 4, packetBuffer, 0, size); MapleAes.Transform(packetBuffer, m_riv); Shanda.DecryptTransform(packetBuffer); m_offset -= size + 4; if (m_offset > 0) { Buffer.BlockCopy(m_buffer, size + 4, m_buffer, 0, m_offset); } OnPacket?.Invoke(new CInPacket(packetBuffer)); } }
private void PacketsQueueWorker() { while (_isDisposed == false) { var tuple = _packetsQueue.Take(); OnPacket?.Invoke(tuple.Item1, tuple.Item2, tuple.Item3);//module, command, packet } }
private void PacketsQueueWorker() { while (!_isDisposed) { var tuple = _packetsQueue.Take(); OnPacket?.Invoke(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4);//context, module, command, packet } }
public void RegistPacketAndResponFunc <T>(int packid, OnPacket onPacket = null) where T : class { readFunSets.Add(packid, TryRead <T>); writeFunSets.Add(packid, TryWrite <T>); typeIdSets.Add(typeof(T), packid); if (onPacket != null) { onPacketSets.Add(packid, onPacket); } }
private static void StartThread(Queue <byte[]> packets, OnPacket callback, IConnection connection) { new Thread(() => { byte[] packet = null; while (DoStuff(packets, ref packet)) { callback(connection, packet); } }).Start(); }
// Methods /// <summary> /// Adds a packet to the <see cref="Rewtek.GameLibrary.Network.PacketHandler"/>. /// </summary> /// <param name="header">The header of the packet.</param> /// <param name="packet">The packet.</param> /// <returns>True if the packet has been added. Otherwise, false.</returns> public bool AddPacket(int header, OnPacket packet) { if (!_packets.ContainsKey(header)) { _packets.Add(header, packet); return true; } else { Logger.Log("Packet {0} has already been added!", header); return false; } }
// Methods /// <summary> /// Adds a packet to the <see cref="Rewtek.GameLibrary.Network.PacketHandler"/>. /// </summary> /// <param name="header">The header of the packet.</param> /// <param name="packet">The packet.</param> /// <returns>True if the packet has been added. Otherwise, false.</returns> public bool AddPacket(int header, OnPacket packet) { if (!_packets.ContainsKey(header)) { _packets.Add(header, packet); return(true); } else { Logger.Log("Packet {0} has already been added!", header); return(false); } }
public TcpPacketHandler(OnPacket onPacket, Action <Exception> onError) { if (onPacket == null) { throw new ArgumentNullException("onPacket"); } this._onPacket = onPacket; if (onError == null) { throw new ArgumentNullException("onError"); } this._onError = onError; ResetPacket(); }
private void HandleConnection(System.Net.Sockets.TcpClient client) { NetworkStream stream = client.GetStream(); while (client.Connected) { if (stream.DataAvailable == false) { Thread.Sleep(100); } byte[] buffer = new byte[client.ReceiveBufferSize]; int bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize); string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); OnPacket?.Invoke(dataReceived); Thread.Sleep(100); } }
private void _proc_callback() { try { var buffer = new List <byte>(); byte[] recvData = new byte[BufferSize]; int size = 0; while (true) { int count = 0; Exception lastException = null; try { count = Receive(recvData); } catch (Exception ex) { lastException = ex; } if (lastException != null) { OnPacket?.Invoke(null, new QueryMasterException("Receive failed", lastException)); break; } if (count > 0) { buffer.AddRange(recvData.Take(count)); while (RconUtil.IsPacket(buffer.ToArray(), out size)) { var packet = buffer.Take(size).ToArray(); OnPacket?.Invoke(packet, null); buffer.RemoveRange(0, size); } } else { OnPacket?.Invoke(null, new QueryMasterException("Receive failed because socket was shutdown by remote host")); break; } } } catch (Exception) { } }
public TcpTransport(string hostname, int port, OnPacket onPacket, OnDisconnect onDisconnect) { _bQuit = false; _client = new TcpClient(); _client.NoDelay = true; _client.ReceiveBufferSize = 2048; _client.SendBufferSize = 2048; _client.ReceiveTimeout = 0; _client.SendTimeout = 30000; _client.LingerState = new LingerOption(true, 30); _client.Connect(hostname, port); //m_stream = m_client.GetStream(); _onPacket = onPacket; _onDisconnect = onDisconnect; DoHandShake(); StartThread("JDbg.TcpTransport"); }
public SACNListener(UInt16 universeID) { Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPAddress localAddress = IPAddress.Any; EndPoint endPoint = new IPEndPoint(localAddress, SACNCommon.SACN_PORT); Socket.Bind(endPoint); MulticastOption option = new MulticastOption(SACNCommon.GetMulticastAddress(universeID), localAddress); Socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, option); Token = new CancellationToken(); ListenTask = Task.Factory.StartNew(() => { byte[] buffer = new byte[SACNPacket.MAX_PACKET_SIZE]; EndPoint remoteEP = new IPEndPoint(SACNCommon.GetMulticastAddress(universeID), SACNCommon.SACN_PORT); ArraySegment <byte> segment = new ArraySegment <byte>(buffer); while (!Token.IsCancellationRequested) { if (Socket.Available > 0) { try { int bytesReceived = Socket.ReceiveFrom(buffer, ref remoteEP); SACNPacket packet = SACNPacket.Parse(segment.Array); OnPacket?.Invoke(this, packet); } catch (SocketException e) { Console.Error.WriteLine(e.ToString()); Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); } } } }); }
/// <param name="callback">The callback you want to get dispatched when a packet gets received</param> public void SetCallback(OnPacket callback) { _callback = callback; }
/// <param name="connection">The connection you want to assign this thread to</param> /// <param name="callback">The callback you want to get dispatched when a packet gets received</param> public ThreadLauncher(IConnection connection, OnPacket callback) { _callback = callback; _parent = connection; }
public async Task Start() { await using var ctx = new NovaContext(); await ctx.EnsureUpdatedAsync(); _server.Start(); RegisterAssembly(typeof(Server).Assembly); RegisterAssembly(Assembly.GetEntryAssembly()); _server.NewConnection += point => { var connection = new Connection(point, _server); Connections.Add(connection); OnConnection?.Invoke(connection); }; _server.Disconnection += point => { var connection = Connections.FirstOrDefault(c => c.EndPoint.Equals(point)); if (connection == default) { return; } Connections.Remove(connection); OnDisconnect?.Invoke(connection); }; _server.PacketReceived += (point, bytes) => { var connection = Connections.FirstOrDefault(c => c.EndPoint.Equals(point)); if (connection == default) { Logger.Warning($"{point} is not connected but we still got data from them!"); return; } using var stream = new MemoryStream(bytes); using var reader = new BitReader(stream); var id = (MessageIdentifiers)reader.Read <byte>(); if (id != MessageIdentifiers.UserPacketEnum) { Logger.Error($"Invalid packet: {id}"); return; } HandlePacket(reader, connection); reader.BaseStream.Position = 0; OnPacket?.Invoke(connection, reader); }; var request = ctx.WorldServerRequests.FirstOrDefault(w => w.SpecificationId == Id); if (request != default) { Logger.Information($"Request found for {Id}"); request.State = WorldServerRequestState.Complete; await ctx.SaveChangesAsync(); } await ctx.DisposeAsync(); while (true) { var command = Console.ReadLine(); } }
protected void InvokeOnPacket(CInPacket packet) => OnPacket?.Invoke(packet);
/// <summary> /// Unregister the event /// </summary> /// <param name="Event">Event to unregister</param> public static void Unregister(OnPacket Event) { if (ToCall.Contains(Event)) ToCall.Remove(Event); }
/// <summary> /// Register an OnPacket event to the server /// </summary> /// <param name="Event">OnPacket Delegate to register</param> public static void Register(OnPacket Event) { ToCall.Add(Event); }
void Device_OnPacketArrival(object sender, CaptureEventArgs e) { Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); if (packet == null || !(packet is EthernetPacket)) { return; } EthernetPacket et = (EthernetPacket)packet; if (et.PayloadPacket == null || !(packet.PayloadPacket is IpPacket)) { return; } IpPacket ip = (IpPacket)et.PayloadPacket; if (ip == null || ip.PayloadPacket == null) { return; } packet = ip.PayloadPacket; switch (ip.Protocol) { case IPProtocolType.TCP: { TcpPacket p = (TcpPacket)packet; IPEndPoint source = new IPEndPoint(ip.SourceAddress, p.SourcePort); IPEndPoint dest = new IPEndPoint(ip.DestinationAddress, p.DestinationPort); if (_HasFilters && !IsAllowedPacket(source, dest, IPProtocolType.TCP)) { return; } OnPacket?.Invoke(this, ip.Protocol, et); if (_SyncPackets.Count > 45000) { GC.Collect(); Thread.Sleep(1); } _SyncPackets.TryAdd(new TcpStreamStack.ResumePacket() { Date = e.Packet.Timeval.Date, HwSource = et.SourceHwAddress, IpSource = source, HwDest = et.DestinationHwAddress, IpDest = dest, Tcp = p }); break; } case IPProtocolType.UDP: { UdpPacket p = (UdpPacket)packet; IPEndPoint source = new IPEndPoint(ip.SourceAddress, p.SourcePort); IPEndPoint dest = new IPEndPoint(ip.DestinationAddress, p.DestinationPort); if (_HasFilters && !IsAllowedPacket(source, dest, IPProtocolType.UDP)) { return; } OnPacket?.Invoke(this, ip.Protocol, et); break; } default: { IPEndPoint source = new IPEndPoint(ip.SourceAddress, 0); IPEndPoint dest = new IPEndPoint(ip.DestinationAddress, 0); if (_HasFilters && !IsAllowedPacket(source, dest, IPProtocolType.UDP)) { return; } OnPacket?.Invoke(this, ip.Protocol, et); break; } } }
/// <summary> /// Zajmuje sie sprawdzaniem czy cos jest na gniezdzie, wczytywaniem naglowka /// oraz calych pakietow /// </summary> private void go() { try { GaduPacketHeader header = new GaduPacketHeader(); // naglowek while (true) { if (!tcpClient.Connected || tcpClient.GetStream().DataAvailable == false || work == false) { // jezeli na gniezdzie nie ma 8 pelnych bajtow lub gniazdo nie jest podlaczone to Thread.Sleep(sleepTime); // czekamy na nowe pakiety continue; // i przechodzimy do nastepnej iteracji } header.read(tcpClient.GetStream(), 8); // czytamy naglowek if (OnPacket != null) { OnPacket.BeginInvoke(header, null, null); } switch (header.Type) { case GaduPacketConstans.GG_RECV_MSG: // ktos przyslal nam wiadomosc GaduPacketRecieveMessage msg = new GaduPacketRecieveMessage(); msg.read(tcpClient.GetStream(), header.Length); // wczytujemy wiadomosc if (OnRecieveMessage != null) // jezeli ktos podstawil swoja funkcje pod event { OnRecieveMessage.BeginInvoke(msg, null, null); // to ja wywolujemy podstawiajac jako argument pakiet z wiadomoscia } break; case GaduPacketConstans.GG_SEND_MSG_ACK: // odebralismy pakiet potwierdzajacy wiadomosc GaduPacketMessageAck ack = new GaduPacketMessageAck(); ack.read(tcpClient.GetStream(), header.Length); // wczytaj pakiet if (OnRecieveMessageAck != null) { OnRecieveMessageAck.BeginInvoke(ack, null, null); // wywolaj event } break; case GaduPacketConstans.GG_PONG: // otrzymalismy pakiet GG_PONG z servera if (OnPong != null) { OnPong.BeginInvoke(null, null); } break; case GaduPacketConstans.GG_LOGIN_OK: // otrzymalismy pakiet informujacy nas o tym ze logowanie sie powiodlo if (header.Length == 1) { tcpClient.GetStream().ReadByte(); // jeden bajt, ktory nie zawsze musi sie pojawic, przeznaczenie nie poznane } if (OnLoginOK != null) { OnLoginOK.BeginInvoke(null, null); // wywolaj event } break; case GaduPacketConstans.GG_NEED_EMAIL: // server chce abysmy uzupelnili e-mail w naszych danych if (OnLoginNeedEmail != null) { OnLoginNeedEmail.BeginInvoke(null, null); // wywolaj event } break; case GaduPacketConstans.GG_LOGIN_FAILED: // logowanie sie nie powiodlo if (OnLoginFailed != null) { OnLoginFailed.BeginInvoke(null, null); // wywolaj event } break; case GaduPacketConstans.GG_NOTIFY_REPLY77: // otrzymalismy pakiet mowiacy o tym ze ktos zmienil status GaduPacketNotifyReplay77 gaduPacketNotifyReplay77; while (header.Length > 0) // najprawdopodobnie bedzie to zlepek pakietow, a wiec bedziemy je wczytywac po kolei { gaduPacketNotifyReplay77 = new GaduPacketNotifyReplay77(); gaduPacketNotifyReplay77.read(tcpClient.GetStream(), header.Length); header.Length -= gaduPacketNotifyReplay77.getSize(); if (OnGaduNotifyReplay != null) { OnGaduNotifyReplay.BeginInvoke(gaduPacketNotifyReplay77, null, null); // dla danego pakiety wywolaj event } } break; case GaduPacketConstans.GG_STATUS77: // ktos zmienil status na gg GaduPacketStatus77 gaduPacketStatus77 = new GaduPacketStatus77(); gaduPacketStatus77.read(tcpClient.GetStream(), header.Length); // wczytujemy pakiet if (OnGaduStatus != null) { OnGaduStatus.BeginInvoke(gaduPacketStatus77, null, null); // wywolujemny event } break; case GaduPacketConstans.GG_USERLIST_REPLY: GaduPacketUserListRequest gaduPacketUserlistReplay = new GaduPacketUserListRequest(); gaduPacketUserlistReplay.read(tcpClient.GetStream(), header.Length); if (OnUserListReplay != null) { OnUserListReplay.BeginInvoke(gaduPacketUserlistReplay, null, null); } break; case GaduPacketConstans.GG_PUBDIR50_REPLY: GaduPacketPubDir50 gaduPacketPubDir50 = new GaduPacketPubDir50(); gaduPacketPubDir50.read(tcpClient.GetStream(), header.Length); if (OnPubDirReplay != null) { OnPubDirReplay.BeginInvoke(gaduPacketPubDir50, null, null); } break; case GaduPacketConstans.GG_DISCONNECTING: if (OnGaduDisconnecting != null) { OnGaduDisconnecting.BeginInvoke(null, null); } break; case GaduPacketConstans.GG_DISCONNECTING2: if (OnGaduDisconnecting != null) { OnGaduDisconnecting.BeginInvoke(null, null); } break; default: // jezeli otrzymalismy jakis pakiet, ktory jeszcze nie jest obslugiwany przez biblioteke byte[] packet = new byte[header.Length]; for (int i = 0; i < header.Length; i++) // to wczytaj tylko pakiet z gniazda i nic z nim nie rob { packet[i] = (byte)tcpClient.GetStream().ReadByte(); } if (OnUnhandledPacket != null) { OnUnhandledPacket.BeginInvoke(header, packet, null, null); } break; } } } catch (ThreadAbortException) { // nie zadreczajmy uzytkownika tym wyjatkiem, w 99% powodowany przez Thread.Abort() } catch (Exception e) { if (Gadu.GaduCriticalError() == false) { throw new GaduRecieverException(e.Message); } } }
static unsafe void Main(string[] args) { Decoder decoder = new Decoder(); decoder.Initialize(); // decoder.Start("1.h264"); decoder.Start("rtmp://localhost:1935/live/test"); OnPacket onPacket = (packet) => { Console.WriteLine($"length: {packet->size}"); byte[] data = new byte[packet->size]; Marshal.Copy((IntPtr)packet->data, data, 0, packet->size); // Console.WriteLine("data: " + string.Concat(data.Select(b => string.Format("0x{0},", b.ToString("X2"))).ToArray())); byte[] NALHeader = new byte[] { 0xAA, 0xBB, 0xCC, 0xDD }; int startIndex = 0; int pos; while ((pos = data.IndexOf(NALHeader, startIndex)) >= 0) { byte[] content = new byte[4]; Array.Copy(data, pos + 4, content, 0, 4); int length = BitConverter.ToInt32(content, 0); content = new byte[length]; Buffer.BlockCopy(data, pos + 4 + 4, content, 0, length); string userData = System.Text.Encoding.UTF8.GetString(Decompress(content)); Console.WriteLine($"SEI length: {length}, {userData}"); startIndex = pos + 4 + 4 + length; } }; OnFrame onFrame = (frame) => { Mat mat = new Mat(frame->height, frame->width, MatType.CV_8UC3, new Scalar(0, 0, 0)); mat = mat.CvtColor(ColorConversionCodes.BGR2YUV_I420); IntPtr ptr = mat.Data; int length1 = frame->linesize[0] * frame->height; byte[] data = new byte[length1]; Marshal.Copy((IntPtr)frame->data[0], data, 0, length1); for (int i = 0; i < frame->height; ++i, ptr += frame->width) { Marshal.Copy(data, frame->linesize[0] * i, ptr, frame->width); } int length2 = frame->linesize[1] * frame->height / 2; data = new byte[length2]; Marshal.Copy((IntPtr)frame->data[1], data, 0, length2); for (int i = 0; i < frame->height / 2; ++i, ptr += frame->width / 2) { Marshal.Copy(data, frame->linesize[1] * i, ptr, frame->width / 2); } int length3 = frame->linesize[2] * frame->height / 2; data = new byte[length3]; Marshal.Copy((IntPtr)frame->data[2], data, 0, length3); for (int i = 0; i < frame->height / 2; ++i, ptr += frame->width / 2) { Marshal.Copy(data, frame->linesize[2] * i, ptr, frame->width / 2); } mat = mat.CvtColor(ColorConversionCodes.YUV2BGR_I420); Cv2.ImShow($"mat", mat); Cv2.WaitKey(0); }; while (decoder.Decode(onPacket, null)) { } decoder.Stop(); decoder.Dispose(); }
// Called when data has been read from the stream. private void OnRead(IAsyncResult result) { stream.EndRead(result); // If the length of the buffer is 5, we should process the packet header. if (inBuffer.Length == 5) { using (PacketReader reader = new PacketReader(new MemoryStream(inBuffer))) { // Skip the packet ID since we don't need it now. reader.ReadByte(); // Read the length from the packet header. int newLength = reader.ReadInt32(); // Resize the packet buffer to the new length. var tmp = new byte[newLength]; if (newLength < 5) { Disconnect(); return; } inBuffer.CopyTo(tmp, 0); inBuffer = tmp; } // Try to read the enough bytes to fill the packet buffer. // We already have 5 bytes in the buffer, so we read inBuffer.Length - 5. stream.BeginRead(inBuffer, 5, inBuffer.Length - 5, OnRead, null); } // If the length is not 5, we have a whole packet that we should process. else { using (PacketReader reader = new PacketReader(new MemoryStream(inBuffer))) { // Read the packet header. byte id = reader.ReadByte(); int length = reader.ReadInt32(); // Create a new instance of the packet we received. IServerPacket packet = PacketResolver.Create((PacketType)id); if (packet != null) { // Read the packet and print its info. packet.Read(reader); // Debug.Log(string.Format("{0}, {1}", id, length)); // Debug.Log(packet.ToString()); if (OnPacket != null) { OnPacket.Invoke(packet); } } else { // We don't have a definition for the packet type we // received, so we cannot instantiate an instance of it. Debug.Log(string.Format("Unable to create packet {0}", id)); } } // Reset the buffer so we are ready to receive the next packet header. inBuffer = new byte[5]; stream.BeginRead(inBuffer, 0, 5, OnRead, null); } }