Beispiel #1
0
 /// <summary>
 /// Sends the specified payload over TCP.
 /// </summary>
 public static void SendTcp(TcpPacketType type, Action <BitBuffer> payloadWriter)
 {
     _client?.SendTcp(buffer => {
         buffer.Write((byte)type);
         payloadWriter(buffer);
     });
 }
Beispiel #2
0
 /// <summary>
 /// Sends the specified payload over TCP to all clients except (this) host client.
 /// </summary>
 public static void SendTcpToClients(TcpPacketType type, Action <BitBuffer> payloadWriter)
 {
     if (!NetworkUtils.IsClient || _clients.Count > 1)
     {
         SendTcpToAll(serverClient => serverClient.Id != NetworkUtils.LocalId, type, payloadWriter);
     }
 }
Beispiel #3
0
 /// <summary>
 /// Sends the specified payload over TCP to the specified client.
 /// </summary>
 public static void SendTcp(INetworkServerClient recipient, TcpPacketType type, Action <BitBuffer> payloadWriter)
 {
     _server?.SendTcp(((NetworkServerClient)recipient).DoubleClient, buffer => {
         buffer.Write((byte)type);
         payloadWriter(buffer);
     });
 }
Beispiel #4
0
        /// <summary>
        ///  For a frame with normal TPKT start and segments appended.
        /// </summary>
        /// <param name="payload">Actual payload of this frame</param>
        /// <param name="length">The length that TPKT header indicate(header itself is exclude)</param>
        private void BuildSegments(ByteArraySegment payload, int length)
        {
            HasSegments = true;

            // Let the length of original TKPT payload without segments
            // be input param length which indicate the TPKT's payload length.
            int segLen = payload.Length - length;

            payload.Length = length;

            if (segLen > 0)
            {
                ByteArraySegment segs = payload.EncapsulatedBytes();
                // The rest segments may be the next TPKT beginning which includes TPKT header.
                //  var potentialHeader = segs;// new ByteArraySegment(segs);
                //segs.Length = TpktFileds.TpktHeaderLength;
                // segs may contain multiple TPKT segments
                byte[] headerRawBytes = segs.ActualBytes().Take(TpktFileds.HeaderLength).ToArray();

                TcpPacketType type = (TcpPacketType)(BigEndianBitConverter.Big.ToInt16(headerRawBytes, 0));
                switch (type)
                {
                case TcpPacketType.Tpkt:
                    // LastSegment = false;
                    int tpktLen = BigEndianBitConverter.Big.ToInt16(headerRawBytes,
                                                                    TpktFileds.ReservedLength + TpktFileds.VersionLength
                                                                    );
                    BuildSegments(segs, tpktLen, segLen);
                    break;

                default:
                    break;
                }
            }
            else
            {
                ByteArraySegment segs = new ByteArraySegment(payload.Bytes);
                BuildSegments(segs, this.Length, segs.Length);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Sends the specified payload over TCP to all clients which pass the specified filter.
        /// </summary>
        public static void SendTcpToAll(Predicate <INetworkServerClient> filter, TcpPacketType type,
                                        Action <BitBuffer> payloadWriter)
        {
            if (_server == null)
            {
                return;
            }

            using (_resettingByteBuffer) {
                _resettingByteBuffer.Write((byte)type);
                payloadWriter(_resettingByteBuffer);
                // ReSharper disable once ConvertToLocalFunction
                Action <BitBuffer> realWriter = buffer => buffer.Write(_resettingByteBuffer.Array,
                                                                       0, _resettingByteBuffer.Size);

                foreach (NetworkServerClient serverClient in _clients)
                {
                    if (filter(serverClient))
                    {
                        _server.SendTcp(serverClient.DoubleClient, realWriter);
                    }
                }
            }
        }
Beispiel #6
0
 public TcpPacket(TcpPacketType requestType)
 {
     this.PacketType = requestType;
     data = new List<byte[]>();
 }
Beispiel #7
0
 /// <summary>
 /// Sets the handler for a specific (TCP) packet type.
 /// </summary>
 public static void SetTcpHandler(TcpPacketType type, [CanBeNull] Action <BitBuffer> handler)
 {
     TcpHandlers[(byte)type] = handler;
 }
Beispiel #8
0
 /// <summary>
 /// Sends the specified payload over TCP to all clients except one.
 /// </summary>
 public static void SendTcpToAll(byte excludingId, TcpPacketType type, Action <BitBuffer> payloadWriter)
 {
     SendTcpToAll(serverClient => serverClient.Id != excludingId, type, payloadWriter);
 }
Beispiel #9
0
 /// <summary>
 /// Sets the handler for a specific (TCP) packet type.
 /// </summary>
 public static void SetTcpHandler(TcpPacketType type, [CanBeNull] OnPacketReceived handler)
 {
     TcpHandlers[(byte)type] = handler;
 }
Beispiel #10
0
        public void AcceptCallback(IAsyncResult ar)
        {
            //Signal the main thread to continue.
            allDone.Set();

            //Get the socket that handles the client request.
            TcpListener   listener      = (TcpListener)ar.AsyncState;
            TcpClient     client        = listener.EndAcceptTcpClient(ar);
            NetworkStream newworkStream = null;

            if (client != null)
            {
                Console.WriteLine("Received connection!");
                newworkStream = client.GetStream();

                Byte[] header = new Byte[1];
                int    length;
                int    receivedDataLength = 0;
                if ((length = newworkStream.Read(header, 0, header.Length)) != 0)
                {
                    receivedDataLength += length;
                    TcpPacketType packetType = (TcpPacketType)Enum.ToObject(typeof(TcpPacketType), header[0]);
                    if (packetType == TcpPacketType.Upload)
                    {
                        Byte[] nameLengthBytes = new Byte[4];
                        if ((length = newworkStream.Read(nameLengthBytes, 0, nameLengthBytes.Length)) != 0)
                        {
                            receivedDataLength += length;
                            int    nameLength = BitConverter.ToInt32(nameLengthBytes, 0);
                            Byte[] nameBytes  = new Byte[nameLength];
                            if ((length = newworkStream.Read(nameBytes, 0, nameBytes.Length)) != 0)
                            {
                                receivedDataLength += length;
                                string name = System.Text.Encoding.UTF8.GetString(nameBytes);
                                using (Stream stream = new FileStream(System.IO.Path.Combine(filePath, name), FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    Byte[] bytes = new Byte[1024];
                                    while ((length = newworkStream.Read(bytes, 0, bytes.Length)) != 0)
                                    {
                                        stream.Write(bytes, 0, length);
                                    }
                                }
                            }
                        }
                        //byte[] receivedData = new byte[4];
                        //receivedData = BitConverter.GetBytes(receivedDataLength);
                        //newworkStream.Write(receivedData, 0, 4);
                    }
                    else if (packetType == TcpPacketType.Get)
                    {
                        List <string> fileNames  = new List <string>();
                        DirectoryInfo directInfo = new DirectoryInfo(filePath);
                        foreach (FileInfo fileInfo in directInfo.GetFiles())
                        {
                            if (fileInfo.Extension == ".mp3" || fileInfo.Extension == ".flv")
                            {
                                fileNames.Add(fileInfo.Name);
                            }
                        }
                        StringBuilder sb = new StringBuilder();
                        if (fileNames.Count > 0)
                        {
                            for (int i = 0; i < fileNames.Count - 1; i++)
                            {
                                sb.Append(fileNames[i] + "#");
                            }
                            sb.Append(fileNames[fileNames.Count - 1]);
                        }
                        Byte[] dataToSend = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                        newworkStream.Write(dataToSend, 0, dataToSend.Length);
                        newworkStream.Flush();
                    }

                    else if (packetType == TcpPacketType.Delete)
                    {
                        List <string> result = new List <string>();
                        Byte[]        buffer = new Byte[1024];
                        int           byteRead;
                        StringBuilder sb = new StringBuilder();
                        while ((byteRead = newworkStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            sb.Append(System.Text.Encoding.UTF8.GetString(buffer));
                        }
                        string songNames = sb.ToString().TrimEnd('\0');
                        result = songNames.Split('#').ToList();

                        DirectoryInfo director = new DirectoryInfo(filePath);
                        if (director.Exists)
                        {
                            List <FileInfo> fileInfo = director.GetFiles().ToList();
                            foreach (string name in result)
                            {
                                FileInfo info = fileInfo.Find(r => r.Name == name);
                                if (info != null && !IsFileLocked(info))
                                {
                                    info.Delete();
                                }
                            }
                        }
                    }
                }
                newworkStream.Close();
                client.Close();
            }


            allDone.Set();
        }
Beispiel #11
0
 public TcpPacket(TcpPacketType requestType)
 {
     this.PacketType = requestType;
     data            = new List <byte[]>();
 }