コード例 #1
0
        private void GetDownloadFileSize(FileTransmitState state)
        {
            var split = Encoding.UTF8.GetBytes("|")[0];

            for (var i = 0; i < state.Buffer.Length; i++)
            {
                if (state.Buffer[i] == split)
                {
                    //前三个字节分别是版本,响应代码,保留位
                    var fileLengthStr = Encoding.UTF8.GetString(state.Buffer, 3, i - 3);
                    int filelength;
                    if (int.TryParse(fileLengthStr, out filelength))
                    {
                        state.FileSize = filelength;
                        //重置Buffer为文件数据,去掉头部
                        //var newBuffer = new byte[state.Buffer.Length - i - 1];
                        var newBuffer  = new byte[BufferSize];
                        var currBuffer = state.Buffer.Skip(i + 1).ToArray();
                        state.DealingByteCount = currBuffer.Length;
                        currBuffer.CopyTo(newBuffer, 0);
                        state.Buffer = newBuffer;

                        break;
                    }
                    else
                    {
                        throw new Exception("响应格式不正确");
                    }
                }
            }
        }
コード例 #2
0
 /// <summary>
 /// 启动异步读取文件
 /// </summary>
 /// <param name="state"></param>
 private void BeginTransmit(FileTransmitState state)
 {
     try
     {
         var readFileBytes = 0;
         var fileStream    = new FileStream(state.FileInfo.FullName, FileMode.Open,
                                            FileAccess.Read, FileShare.Read, BufferSize,
                                            FileOptions.Asynchronous);
         state.TransmitedByteCount = readFileBytes;
         state.FileStream          = fileStream;
         state.Buffer = new byte[BufferSize];
         //TODO buffer size
         fileStream.BeginRead(state.Buffer, 0, BufferSize, AfterReadFileToBuffer,
                              //new FileTransmitState()
                              //{
                              //    FileStream = fileStream,
                              //    Buffer = new byte[BufferSize],
                              //    Connection = state.Connection,
                              //    TransmitedByteCount = readFileBytes,
                              //    FileInfo = state.FileInfo,
                              //    FileSize = state.FileInfo.Length,
                              //});
                              state);
     }
     catch (Exception e)
     {
         Logging.LogUsefulException(e);
     }
 }
コード例 #3
0
        public void Upload(string filePath, Action<FileTransmitState> callback)
        {
            if (string.IsNullOrEmpty(filePath)) filePath = GetFileName();
            //var FileInfo = new FileInfo(filePath);
            //var fName = FileInfo.Name;
            //byte[] preBuffer;
            //using (var memoryStream = new MemoryStream())
            //{
            //    using (BinaryWriter writer = new BinaryWriter(memoryStream))
            //    {

            //        writer.Write(fName);

            //        //writer.Write(md5Hash);
            //    }
            //    preBuffer = memoryStream.ToArray();
            //}

            FileTransmitState state = null;
            try
            {
                IPAddress ipAddress;
                bool parsed = IPAddress.TryParse(Config.ServerAddress, out ipAddress);
                if (!parsed)
                {
                    IPHostEntry ipHostInfo = Dns.GetHostEntry(Config.ServerAddress);
                    ipAddress = ipHostInfo.AddressList[0];
                }
                Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var ipEndPoint = new IPEndPoint(ipAddress, Config.ServerPort);
                var fileInfo = new FileInfo(filePath);
                state = new FileTransmitState
                {
                    Connection = clientSocket,
                    FileInfo = fileInfo,
                    FileSize = fileInfo.Length,
                    FileName = fileInfo.Name,
                    AfterTransmitCallback = callback
                };
                //clientSocket.BeginConnect(ipEndPoint, SendHandshakeMsg, new Tuple<string, Socket>(filePath, clientSocket));
                state.Connection.BeginConnect(ipEndPoint, SendHandshakeMsg, state);
            }
            catch (Exception ex)
            {
                Logging.LogUsefulException(ex);
                if (state != null)
                {
                    try
                    {
                        state.Connection.Shutdown(SocketShutdown.Both);
                        state.Connection.Close();
                    }
                    catch (Exception e)
                    {
                        Logging.LogUsefulException(e);
                    }
                }
            }
        }
コード例 #4
0
        public void Upload(Socket connection, byte[] handshakeMsg, int handshakeMsgLength)
        {
            if (closed)
            {
                return;
            }
            lastActivity = DateTime.Now;

            var state = new FileTransmitState
            {
                Connection = connection,
            };

            try
            {
                byte[] response    = { 1, 0x10, 0 };//Succeed msg
                var    fileInfoStr = Encoding.UTF8.GetString(handshakeMsg, 6, handshakeMsgLength - 6);

                if (string.IsNullOrEmpty(fileInfoStr))
                {
                    Logging.Error("FileInfo Error,response X'40'");
                    response[1] = 0x40; //Client Msg Error
                }
                else
                {
                    var fileInfoArray = fileInfoStr.Split('|');
                    if (fileInfoArray.Length != 2)
                    {
                        Logging.Error("FileInfo Error,response X'40'");
                        response[1] = 0x40; //Client Msg Error
                    }
                    else
                    {
                        state.DealingByteCount = 0;
                        state.Buffer           = null;
                        state.FileName         = fileInfoArray[0];
                        state.FileSize         = Convert.ToInt32(fileInfoArray[1]);
                        if (!Util.CheckDiskSpace(FileServerDir, state.FileSize))
                        {
                            response[1] = 0x51; //Not enough diskspace Msg Error
                        }
                    }
                }
                if (response[1] != 0x10)
                {
                    state.Connection.BeginSend(response, 0, response.Length, 0, UploadFinishingCallBack, state);
                    return;
                }
                state.Connection.BeginSend(response, 0, response.Length, 0, UploadHandshakeSendCallback, state);
            }
            catch (Exception e)
            {
                Logging.Debug("握手过程中发生异常");
                Logging.LogUsefulException(e);
                state.Close();
            }
        }
コード例 #5
0
        public void Upload(Socket connection, byte[] handshakeMsg, int handshakeMsgLength)
        {
            if (closed)
            {
                return;
            }
            lastActivity = DateTime.Now;

            var state = new FileTransmitState
            {
                Connection = connection,
            };
            try
            {
                byte[] response = { 1, 0x10, 0 };//Succeed msg
                var fileInfoStr = Encoding.UTF8.GetString(handshakeMsg, 6, handshakeMsgLength - 6);

                if (string.IsNullOrEmpty(fileInfoStr))
                {
                    Logging.Error("FileInfo Error,response X'40'");
                    response[1] = 0x40; //Client Msg Error
                }
                else
                {
                    var fileInfoArray = fileInfoStr.Split('|');
                    if (fileInfoArray.Length != 2)
                    {
                        Logging.Error("FileInfo Error,response X'40'");
                        response[1] = 0x40; //Client Msg Error
                    }
                    else
                    {
                        state.DealingByteCount = 0;
                        state.Buffer = null;
                        state.FileName = fileInfoArray[0];
                        state.FileSize = Convert.ToInt32(fileInfoArray[1]);
                        if (!Util.CheckDiskSpace(FileServerDir, state.FileSize))
                        {
                            response[1] = 0x51; //Not enough diskspace Msg Error
                        }
                    }
                }
                if (response[1] != 0x10)
                {
                    state.Connection.BeginSend(response, 0, response.Length, 0, UploadFinishingCallBack, state);
                    return;
                }
                state.Connection.BeginSend(response, 0, response.Length, 0, UploadHandshakeSendCallback, state);
            }
            catch (Exception e)
            {
                Logging.Debug("握手过程中发生异常");
                Logging.LogUsefulException(e);
                state.Close();
            }
        }
コード例 #6
0
 private void Close(FileTransmitState transmitState)
 {
     lock (this)
     {
         if (closed)
         {
             return;
         }
         closed = true;
     }
     transmitState?.Close();
 }
コード例 #7
0
 private void WriteFile(FileTransmitState state)
 {
     if (state.FileStream == null)
     {
         var filePath = Path.Combine(DownloadFileDir, state.FileName);
         CreateDir(filePath);
         var writer = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write, BufferSize,
                                     FileOptions.Asynchronous);
         state.FileInfo   = new FileInfo(filePath);
         state.FileStream = writer;
     }
     state.FileStream.BeginWrite(state.Buffer, 0,
                                 state.DealingByteCount, DownLoadWriteFileCallBack, state);
 }
コード例 #8
0
        public void DownLoad(string filePath, Action <FileTransmitState> callback)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = GetFileName();
            }
            FileTransmitState state = null;

            try
            {
                IPAddress ipAddress;
                bool      parsed = IPAddress.TryParse(Config.ServerAddress, out ipAddress);
                if (!parsed)
                {
                    IPHostEntry ipHostInfo = Dns.GetHostEntry(Config.ServerAddress);
                    ipAddress = ipHostInfo.AddressList[0];
                }
                var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var ipEndPoint   = new IPEndPoint(ipAddress, Config.ServerPort);
                var fileInfo     = new FileInfo(filePath);
                state = new FileTransmitState
                {
                    Connection = clientSocket,
                    FileInfo   = fileInfo,
                    //FileSize = fileInfo.Length,
                    FileName = fileInfo.Name,
                    AfterTransmitCallback = callback
                };
                state.Connection.BeginConnect(ipEndPoint, SendDownloadHandshakeMsg, state);
            }
            catch (Exception ex)
            {
                Logging.LogUsefulException(ex);
                if (state != null)
                {
                    try
                    {
                        state.Connection.Shutdown(SocketShutdown.Both);
                        state.Connection.Close();
                    }
                    catch (Exception e)
                    {
                        Logging.LogUsefulException(e);
                    }
                }
            }
        }
コード例 #9
0
        /// <summary>
        /// 文件下载服务处理
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="handshakeMsg"></param>
        /// <param name="handshakeMsgLength"></param>
        public void Download(Socket connection, byte[] handshakeMsg, int handshakeMsgLength)
        {
            if (closed)
            {
                return;
            }
            lastActivity = DateTime.Now;

            var state = new FileTransmitState
            {
                Connection = connection,
            };
            try
            {
                List<byte> response = new List<byte> { 1, 0x10, 0 };//Succeed msg
                var fileInfoStr = Encoding.UTF8.GetString(handshakeMsg, 6, handshakeMsgLength - 6);

                if (string.IsNullOrEmpty(fileInfoStr))
                {
                    Logging.Error("FileInfo Error,response X'40'");
                    response[1] = 0x41; //Client Msg Error
                }
                else
                {

                    var path = Path.Combine(FileServerDir, fileInfoStr);
                    if (!File.Exists(path))
                    {
                        response[1] = 0x44; //File Not Found
                    }
                    else
                    {
                        state.FileInfo = new FileInfo(path);
                        state.FileSize = state.FileInfo.Length;
                        state.DealingByteCount = 0;


                        state.FileName = state.FileInfo.Name;
                        //使用“|做分隔符”
                        var fileLengthBytes = Encoding.UTF8.GetBytes(state.FileInfo.Length + "|");
                        response.AddRange(fileLengthBytes);
                        state.Buffer = new byte[BufferSize];
                    }
                    //config.FileSize = Convert.ToInt32(fileInfoArray[1]);
                }
                state.Connection.Send(response.ToArray());
                if (response[1] != 0x10)
                {
                    //Error
                    state.Close();
                }
                else
                {

                    state.Connection.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None,
                        After2ndHandshakeCallback, state);
                }
            }
            catch (Exception e)
            {
                Logging.Debug("握手过程中发生异常");
                Logging.LogUsefulException(e);
                state.Close();
            }
        }
コード例 #10
0
 private void Close(FileTransmitState transmitState)
 {
     lock (this)
     {
         if (closed)
         {
             return;
         }
         closed = true;
     }
     transmitState?.Close();
 }
コード例 #11
0
        private void WriteFile(FileTransmitState state)
        {

            if (state.FileStream == null)
            {
                var filePath = Path.Combine(DownloadFileDir, state.FileName);
                CreateDir(filePath);
                var writer = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write, BufferSize,
                    FileOptions.Asynchronous);
                state.FileInfo = new FileInfo(filePath);
                state.FileStream = writer;
            }
            state.FileStream.BeginWrite(state.Buffer, 0,
                state.DealingByteCount, DownLoadWriteFileCallBack, state);
        }
コード例 #12
0
        private void GetDownloadFileSize(FileTransmitState state)
        {
            var split = Encoding.UTF8.GetBytes("|")[0];

            for (var i = 0; i < state.Buffer.Length; i++)
            {
                if (state.Buffer[i] == split)
                {
                    //前三个字节分别是版本,响应代码,保留位
                    var fileLengthStr = Encoding.UTF8.GetString(state.Buffer, 3, i - 3);
                    int filelength;
                    if (int.TryParse(fileLengthStr, out filelength))
                    {
                        state.FileSize = filelength;
                        //重置Buffer为文件数据,去掉头部
                        //var newBuffer = new byte[state.Buffer.Length - i - 1];
                        var newBuffer = new byte[BufferSize];
                        var currBuffer = state.Buffer.Skip(i + 1).ToArray();
                        state.DealingByteCount = currBuffer.Length;
                        currBuffer.CopyTo(newBuffer, 0);
                        state.Buffer = newBuffer;

                        break;
                    }
                    else
                    {
                        throw new Exception("响应格式不正确");
                    }
                }
            }
        }
コード例 #13
0
 public void DownLoad(string filePath, Action<FileTransmitState> callback)
 {
     if (string.IsNullOrEmpty(filePath)) filePath = GetFileName();
     FileTransmitState state = null;
     try
     {
         IPAddress ipAddress;
         bool parsed = IPAddress.TryParse(Config.ServerAddress, out ipAddress);
         if (!parsed)
         {
             IPHostEntry ipHostInfo = Dns.GetHostEntry(Config.ServerAddress);
             ipAddress = ipHostInfo.AddressList[0];
         }
         var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         var ipEndPoint = new IPEndPoint(ipAddress, Config.ServerPort);
         var fileInfo = new FileInfo(filePath);
         state = new FileTransmitState
         {
             Connection = clientSocket,
             FileInfo = fileInfo,
             //FileSize = fileInfo.Length,
             FileName = fileInfo.Name,
             AfterTransmitCallback = callback
         };
         state.Connection.BeginConnect(ipEndPoint, SendDownloadHandshakeMsg, state);
     }
     catch (Exception ex)
     {
         Logging.LogUsefulException(ex);
         if (state != null)
         {
             try
             {
                 state.Connection.Shutdown(SocketShutdown.Both);
                 state.Connection.Close();
             }
             catch (Exception e)
             {
                 Logging.LogUsefulException(e);
             }
         }
     }
 }
コード例 #14
0
        /// <summary>
        /// 启动异步读取文件
        /// </summary>
        /// <param name="state"></param>
        private void BeginTransmit(FileTransmitState state)
        {
            try
            {
                var readFileBytes = 0;
                var fileStream = new FileStream(state.FileInfo.FullName, FileMode.Open,
                    FileAccess.Read, FileShare.Read, BufferSize,
                    FileOptions.Asynchronous);
                state.TransmitedByteCount = readFileBytes;
                state.FileStream = fileStream;
                state.Buffer = new byte[BufferSize];
                //TODO buffer size
                fileStream.BeginRead(state.Buffer, 0, BufferSize, AfterReadFileToBuffer,
                    //new FileTransmitState()
                    //{
                    //    FileStream = fileStream,
                    //    Buffer = new byte[BufferSize],
                    //    Connection = state.Connection,
                    //    TransmitedByteCount = readFileBytes,
                    //    FileInfo = state.FileInfo,
                    //    FileSize = state.FileInfo.Length,
                    //});
                    state);
            }
            catch (Exception e)
            {

                Logging.LogUsefulException(e);
            }

        }
コード例 #15
0
        /// <summary>
        /// 文件下载服务处理
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="handshakeMsg"></param>
        /// <param name="handshakeMsgLength"></param>
        public void Download(Socket connection, byte[] handshakeMsg, int handshakeMsgLength)
        {
            if (closed)
            {
                return;
            }
            lastActivity = DateTime.Now;

            var state = new FileTransmitState
            {
                Connection = connection,
            };

            try
            {
                List <byte> response = new List <byte> {
                    1, 0x10, 0
                };                                                  //Succeed msg
                var fileInfoStr = Encoding.UTF8.GetString(handshakeMsg, 6, handshakeMsgLength - 6);

                if (string.IsNullOrEmpty(fileInfoStr))
                {
                    Logging.Error("FileInfo Error,response X'40'");
                    response[1] = 0x41; //Client Msg Error
                }
                else
                {
                    var path = Path.Combine(FileServerDir, fileInfoStr);
                    if (!File.Exists(path))
                    {
                        response[1] = 0x44; //File Not Found
                    }
                    else
                    {
                        state.FileInfo         = new FileInfo(path);
                        state.FileSize         = state.FileInfo.Length;
                        state.DealingByteCount = 0;


                        state.FileName = state.FileInfo.Name;
                        //使用“|做分隔符”
                        var fileLengthBytes = Encoding.UTF8.GetBytes(state.FileInfo.Length + "|");
                        response.AddRange(fileLengthBytes);
                        state.Buffer = new byte[BufferSize];
                    }
                    //config.FileSize = Convert.ToInt32(fileInfoArray[1]);
                }
                state.Connection.Send(response.ToArray());
                if (response[1] != 0x10)
                {
                    //Error
                    state.Close();
                }
                else
                {
                    state.Connection.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None,
                                                  After2ndHandshakeCallback, state);
                }
            }
            catch (Exception e)
            {
                Logging.Debug("握手过程中发生异常");
                Logging.LogUsefulException(e);
                state.Close();
            }
        }
コード例 #16
0
        public void Upload(string filePath, Action <FileTransmitState> callback)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = GetFileName();
            }
            //var FileInfo = new FileInfo(filePath);
            //var fName = FileInfo.Name;
            //byte[] preBuffer;
            //using (var memoryStream = new MemoryStream())
            //{
            //    using (BinaryWriter writer = new BinaryWriter(memoryStream))
            //    {

            //        writer.Write(fName);

            //        //writer.Write(md5Hash);
            //    }
            //    preBuffer = memoryStream.ToArray();
            //}

            FileTransmitState state = null;

            try
            {
                IPAddress ipAddress;
                bool      parsed = IPAddress.TryParse(Config.ServerAddress, out ipAddress);
                if (!parsed)
                {
                    IPHostEntry ipHostInfo = Dns.GetHostEntry(Config.ServerAddress);
                    ipAddress = ipHostInfo.AddressList[0];
                }
                Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var    ipEndPoint   = new IPEndPoint(ipAddress, Config.ServerPort);
                var    fileInfo     = new FileInfo(filePath);
                state = new FileTransmitState
                {
                    Connection            = clientSocket,
                    FileInfo              = fileInfo,
                    FileSize              = fileInfo.Length,
                    FileName              = fileInfo.Name,
                    AfterTransmitCallback = callback
                };
                //clientSocket.BeginConnect(ipEndPoint, SendHandshakeMsg, new Tuple<string, Socket>(filePath, clientSocket));
                state.Connection.BeginConnect(ipEndPoint, SendHandshakeMsg, state);
            }
            catch (Exception ex)
            {
                Logging.LogUsefulException(ex);
                if (state != null)
                {
                    try
                    {
                        state.Connection.Shutdown(SocketShutdown.Both);
                        state.Connection.Close();
                    }
                    catch (Exception e)
                    {
                        Logging.LogUsefulException(e);
                    }
                }
            }
        }