コード例 #1
0
        public void CheckDownloadFile()
        {
            string       ftp_uri = $"{Config.Server_Address}/zip_file.zip";
            const string path    = "downloaded_zip_file.zip";

            try
            {
                using (var ftp = new FileTransferProtocol(ftp_uri, path, Config.Username, Config.Password))
                {
                    if (ftp.RequestFileDownload())
                    {
                        Assert.That(ftp.RequestStatusCode == FtpStatusCode.OpeningData || ftp.RequestStatusCode == FtpStatusCode.DataAlreadyOpen);
                        ftp.DownloadFile();
                        Assert.That(ftp.RequestStatusCode == FtpStatusCode.ClosingData);
                        Assert.That(File.Exists(path));
                    }
                    else
                    {
                        throw new ArgumentException("Retrieved stream is invalid.");
                    }
                }
            }
            catch (Exception exception)
            {
                if (exception is WebException)
                {
                    Assert.Fail(exception.Message);
                }
            }
        }
コード例 #2
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                //
                //serialPort1.WriteLine(txtSend.Text);

                //byte[] rtn=System.Text.Encoding.Default.GetBytes(txtSend.Text);
                //serialPort1.Write(rtn, 0, rtn.Length);
                byte[] errData = new byte[] { 0x23, 0x7f, 0x08, 0xab, 0x7f, 0x7e, 0x00, 0x7f, 0xff, 0x7f };
                //serialPort1.Write(errData, 0, errData.Length);

                //FileTransferProtocol x = new FileTransferProtocol();
                byte[] b = FileTransferProtocol.GetFrameFileInfo(0xFF, @"t.txt");

                serialPort1.Write(b, 0, b.Length);
                byte[] c = FileTransferProtocol.GetFrameFileData(255 + 1 + 2 + 4, System.Text.Encoding.Default.GetBytes("你好,CE文件!"));

                serialPort1.Write(c, 0, c.Length);

                byte[] d = FileTransferProtocol.GetFrameFileSendFinish();

                serialPort1.Write(d, 0, d.Length);
            }
            catch (Exception er)
            {
                txtData.Text += string.Format("[异常]:{0}\r\n", er.Message);
            }
        }
コード例 #3
0
        public void CheckListDirectory()
        {
            string ftp_uri = $"{Config.Server_Address}/";

            try
            {
                using (var ftp = new FileTransferProtocol(ftp_uri, null, Config.Username, Config.Password))
                {
                    if (ftp.UpdateDirectoryList())
                    {
                        Assert.That(ftp.RequestStatusCode == FtpStatusCode.OpeningData || ftp.RequestStatusCode == FtpStatusCode.DataAlreadyOpen);
                    }
                    else
                    {
                        throw new ArgumentException("Retrieved stream is invalid.");
                    }
                }
            }
            catch (Exception exception)
            {
                if (exception is WebException)
                {
                    Assert.Fail(exception.Message);
                }
            }
        }
コード例 #4
0
ファイル: Download.cs プロジェクト: doubletruth/FtpClient
 public void Execute(string ftpUri, string path = null, string username = null, string password = null)
 {
     Console.WriteLine("File download beginning...");
     using (var ftp = new FileTransferProtocol(ftpUri, path, username, password))
     {
         try
         {
             if (!ftp.RequestFileDownload())
             {
                 Console.Write(ftp.RequestStatus);
                 return;
             }
             Console.Write(ftp.RequestStatus);
             if (File.Exists(path))
             {
                 Console.WriteLine("A file with the same name already exists. Overwrite file? [y/n]");
                 string userResponse = Console.ReadLine() ?? string.Empty;
                 if (userResponse.ToUpper() != "Y")
                 {
                     Console.WriteLine("File download aborted.");
                     return;
                 }
             }
             ftp.DownloadFile();
             Console.Write(ftp.RequestStatus);
         }
         catch (Exception exception)
         {
             Console.WriteLine($"{ftpUri} download error -> {exception.Message}");
         }
     }
 }
コード例 #5
0
ファイル: Form1.cs プロジェクト: yanzisoft/COMFTP
        private void btnTestMN_Click(object sender, EventArgs e)
        {
            byte[] frame = FileTransferProtocol.GetFrameMNVersionLimited(255, "1234", -1);

            TcpClient tcpclient = new TcpClient(cmbIP.Text, int.Parse(txtPort.Text));

            Stream s = tcpclient.GetStream();

            s.Write(frame, 0, frame.Length);
        }
コード例 #6
0
 public static FileSystemFactory GetInstance(FileTransferProtocol type)
 {
     return(type switch
     {
         FileTransferProtocol.NetworkShare => _windowsSharedFactorySingleton ??= new NetworkShareFileSystemFactory(),
         FileTransferProtocol ftp when
         ftp == FileTransferProtocol.SftpScp ||
         ftp == FileTransferProtocol.LocalSftpScp => _sftpFactorySingleton ??= new SftpFileSystemFactory(),
         _ => throw new ApplicationException("File system manager factory with type \"" + type + "\" does not exist."),
     });
コード例 #7
0
 private void btnUpdate_Click(object sender, EventArgs e)
 {
     try
     {
         byte[] data = FileTransferProtocol.GetFrameMNVersionLimited(int.Parse(txtSend.Text), txtMN.Text, -1);
         serialPort1.Write(data, 0, data.Length);
     }
     catch (Exception er)
     {
     }
 }
コード例 #8
0
ファイル: Form1.cs プロジェクト: yanzisoft/COMFTP
 private void btnRequestClientUpdate_Click(object sender, EventArgs e)
 {
     byte[] frame = FileTransferProtocol.GetFrameWhatIsYourMNandVersion();
     foreach (NetworkStream stream in streamList)
     {
         try
         {
             stream.Write(frame, 0, frame.Length);
         }
         catch
         {
         }
     }
 }
コード例 #9
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            //serialPort1.WriteLine(txtSend.Text);
            //FileTransferProtocol x = new FileTransferProtocol();

            //byte[] b = x.GetFrameFileInfo(@"c:\text.txt".Length, @"c:\text.txt");
            //serialPort1.Write(b, 0, b.Length);
            //byte[] c = x.GetFrameFileData(255 + 1 + 2 + 4, new byte[] { 0x01, 0x02, 0x03, 0xEE, 0xFF });
            //serialPort1.Write(c, 0, c.Length);
            //byte[] d = x.GetFrameFileSendFinish();
            //serialPort1.Write(d, 0, d.Length);

            byte[] data = FileTransferProtocol.GetFrameMessage(txtSend.Text);
            serialPort1.Write(data, 0, data.Length);
        }
コード例 #10
0
ファイル: GetSize.cs プロジェクト: doubletruth/FtpClient
 public void Execute(string ftpUri, string path = null, string username = null, string password = null)
 {
     Console.WriteLine("Getting size...");
     try
     {
         using (var ftp = new FileTransferProtocol(ftpUri, path, username, password))
         {
             ftp.GetSize();
             Console.Write(ftp.RequestStatus);
         }
     }
     catch (Exception exception)
     {
         Console.WriteLine($"{ftpUri} get size error -> {exception.Message}");
     }
 }
コード例 #11
0
 public void Execute(string ftpUri, string path = null, string username = null, string password = null)
 {
     Console.WriteLine("Removing directory...");
     try
     {
         using (var ftp = new FileTransferProtocol(ftpUri, path, username, password))
         {
             ftp.RemoveDirectory();
             Console.Write(ftp.RequestStatus);
         }
     }
     catch (Exception exception)
     {
         Console.WriteLine($"{ftpUri} remove directory error -> {exception.Message}");
     }
 }
コード例 #12
0
        public void CheckGetSize()
        {
            string ftp_uri = $"{Config.Server_Address}/renamed_zip_file.zip";

            try
            {
                using (var ftp = new FileTransferProtocol(ftp_uri, null, Config.Username, Config.Password))
                {
                    ftp.GetSize();
                    Assert.That(ftp.RequestStatusCode == FtpStatusCode.FileStatus);
                }
            }
            catch (Exception exception)
            {
                if (exception is WebException)
                {
                    Assert.Fail(exception.Message);
                }
            }
        }
コード例 #13
0
        public void CheckRemoveDirectory()
        {
            string ftp_uri = $"{Config.Server_Address}/new_directory_renamed";

            try
            {
                using (var ftp = new FileTransferProtocol(ftp_uri, null, Config.Username, Config.Password))
                {
                    ftp.RemoveDirectory();
                    Assert.That(ftp.RequestStatusCode == FtpStatusCode.FileActionOK);
                }
            }
            catch (Exception exception)
            {
                if (exception is WebException)
                {
                    Assert.Fail(exception.Message);
                }
            }
        }
コード例 #14
0
        /// <summary>
        /// Acción para el evento de clic sobre el menu de cada nodo
        /// </summary>
        /// <param name="sender">El sender</param>
        /// <param name="e">Los parametros del evento</param>
        private void menuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView.SelectedNode;

            if (node != null)
            {
                try
                {
                    NetUserFile netUserFile = (NetUserFile)node.Tag;
                    FileTransferProtocol.sendFileRequest(netUserFile.NetUser, netUserFile.FileInformation);
                }
                catch (ThreadAbortException ex)
                {
                    throw ex;
                }
                catch (Exception)
                {
                }
            }
        }
コード例 #15
0
ファイル: Upload.cs プロジェクト: doubletruth/FtpClient
 public void Execute(string ftpUri, string path = null, string username = null, string password = null)
 {
     Console.WriteLine("File upload beginning...");
     if (!File.Exists(path))
     {
         Console.WriteLine($"{ftpUri} upload error -> {path} not found.");
         return;
     }
     using (var ftp = new FileTransferProtocol(ftpUri, path, username, password))
     {
         try
         {
             ftp.UploadFile();
             Console.Write(ftp.RequestStatus);
         }
         catch (Exception exception)
         {
             Console.WriteLine($"{ftpUri} upload error -> {exception.Message}");
         }
     }
 }
コード例 #16
0
        public void CheckRenameFile()
        {
            string       ftp_uri = $"{Config.Server_Address}/uploaded_zip_file.zip";
            const string path    = "renamed_zip_file.zip";

            try
            {
                using (var ftp = new FileTransferProtocol(ftp_uri, path, Config.Username, Config.Password))
                {
                    ftp.Rename();
                    Assert.That(ftp.RequestStatusCode == FtpStatusCode.FileActionOK);
                }
            }
            catch (Exception exception)
            {
                if (exception is WebException)
                {
                    Assert.Fail(exception.Message);
                }
            }
        }
コード例 #17
0
 public void Execute(string ftpUri, string path = null, string username = null, string password = null)
 {
     Console.WriteLine("Listing directory...");
     try
     {
         using (var ftp = new FileTransferProtocol(ftpUri, path, username, password))
         {
             if (ftp.UpdateDirectoryList())
             {
                 Console.WriteLine(ftp.Directory);
             }
             else
             {
                 Console.Write(ftp.RequestStatus);
             }
         }
     }
     catch (Exception exception)
     {
         Console.WriteLine($"{ftpUri} list directory error -> {exception.Message}");
     }
 }
コード例 #18
0
        private void btnTestCOMTCP_Click(object sender, EventArgs e)
        {
            CRC.CRC8 crc = new CRC.CRC8();

            int dataStartIndex = FileTransferProtocol.CommandDataIndex;
            //测试:准备发送新的文件
            string filename = @"c:\abc.txt";

            byte[] FileInfo = FileTransferProtocol.GetFrameFileInfo(255 + 256, filename);

            //帧头

            Trace.Assert(FileInfo[0] == FileTransferProtocol.FrameHead);
            //crc
            //Trace.Assert(FileInfo[1] == crc);
            //命令字
            Trace.Assert(FileInfo[1] == 0x00);
            //文件长度
            Trace.Assert(FileInfo[2] == 0xFF);
            Trace.Assert(FileInfo[3] == 0x01);
            Trace.Assert(FileInfo[4] == 0);
            Trace.Assert(FileInfo[5] == 0);

            byte[] bs = System.Text.Encoding.Default.GetBytes(filename);
            Trace.Assert(FileInfo[6] == bs[0]);
            Trace.Assert(FileInfo[7] == bs[1]);

            //帧偏移
            Trace.Assert((FileInfo[FileInfo.Length - 4] + FileInfo[FileInfo.Length - 3] * 256) == (FileInfo.Length - 1));

            Trace.Assert(FileInfo[FileInfo.Length - 2] == 0x7F);
            Trace.Assert(FileInfo[FileInfo.Length - 1] == 0xFF);

            byte[] data = new byte[] { 0x01, 0x02, 0xFF, 0xEF, 0xCC, 0xDD, 0x00, 0xAA };

            byte[] FileData = FileTransferProtocol.GetFrameFileData(0x01AABBFF, data);

            //帧头
            Trace.Assert(FileData[0] == FileTransferProtocol.FrameHead);
            //帧偏移
            Trace.Assert((FileData[FileData.Length - 3] * 256 + FileData[FileData.Length - 4]) == (FileData.Length - 1));
            //命令字
            Trace.Assert(FileData[1] == 0x1);

            //文件偏移
            Trace.Assert(FileData[2] == 0xFF);
            Trace.Assert(FileData[3] == 0xBB);
            Trace.Assert(FileData[4] == 0xAA);
            Trace.Assert(FileData[5] == 0x01);

            //文件数据
            Trace.Assert(FileData[6] == 0x01);
            Trace.Assert(FileData[7] == 0x02);
            Trace.Assert(FileData[8] == 0xFF);
            Trace.Assert(FileData[9] == 0xEF);

            Trace.Assert(FileData[10] == 0xCC);
            Trace.Assert(FileData[11] == 0xDD);

            //crc
            //byte[] x = new byte[] { 0x02, 0xFF, 0xBB, 0xAA, 0x01, 0x01, 0x02, 0xFF, 0xEF, 0xCC, 0xDD, 0x00, 0xAA, FileData[FileData.Length - 3], FileData[FileData.Length - 2] };

            //Trace.Assert(FileData[1] == crc.Crc(x, 0, x.Length));
            Trace.Assert(FileData[FileData.Length - 1] == 0x7F);

            //文件发送完毕
            byte[] f = FileTransferProtocol.GetFrameFileSendFinish();

            //帧头
            Trace.Assert(f[0] == FileTransferProtocol.FrameHead);
            //帧偏移
            Trace.Assert((f[f.Length - 3] * 256 + f[f.Length - 4]) == f.Length - 1);
            //命令字
            Trace.Assert(f[1] == 0x02);
            //crc
            //Trace.Assert(f[1] == crc.Crc(f, dataStartIndex, f.Length - 3));
            Trace.Assert(f[f.Length - 1] == 0x7F);


            //表示可以新的文件
            byte[] a = FileTransferProtocol.GetFrameWhatIsYourMNandVersion();
            TestCmdFrame(a, 0xFD, crc);

            //表示已经接收数据
            //byte[] Ac = FileTransferProtocol.GetFrameMNAndVersion(1,"123");
            //TestCmdFrame(Ac, 0xFE, crc);

            //表示已经保存文件完毕
            byte[] s = FileTransferProtocol.GetFrameCloseSocket();

            TestCmdFrame(s, 0xFF, crc);
        }
コード例 #19
0
        private void btnSendFile_Click(object sender, EventArgs e)
        {
            //byte[] bytes = System.Text.Encoding.Default.GetBytes(txtSend.Text+"\r");


            try
            {
                if (!serialPort1.IsOpen)
                {
                    serialPort1.PortName = cmPorts.SelectedItem.ToString();
                    serialPort1.Open();
                }
                new Thread(new ThreadStart(delegate()
                {
                    try
                    {
                        string filepath = @"d:\EnumCOMS.exe";

                        FileStream fs = File.Open(filepath, FileMode.Open);

                        //FileTransferProtocol ftp = new FileTransferProtocol();


                        byte[] fi = FileTransferProtocol.GetFrameFileInfo((int)fs.Length, System.IO.Path.GetFileName(filepath));
                        serialPort1.DiscardOutBuffer();
                        serialPort1.Write(fi, 0, fi.Length);

                        int bufferSize = serialPort1.WriteBufferSize / 2;
                        Byte[] bytes   = new Byte[bufferSize];
                        //byte[] bytes = new byte[] { 0x30, 0x31, 0x32, 0x39 ,0x00 };


                        int fullTime    = (int)(fs.Length / (long)bufferSize);
                        int mod         = (int)(fs.Length % (long)bufferSize);
                        Byte[] modBytes = new Byte[mod];


                        for (int i = 0; i < fullTime; i++)
                        {
                            fs.Read(bytes, 0, bufferSize);
                            byte[] data = FileTransferProtocol.GetFrameFileData(i * bufferSize, bytes);
                            serialPort1.Write(data, 0, data.Length);
                        }
                        if (mod != 0)
                        {
                            fs.Read(modBytes, 0, mod);
                            byte[] data = FileTransferProtocol.GetFrameFileData(fullTime * bufferSize, modBytes);
                            serialPort1.Write(data, 0, data.Length);
                        }


                        fs.Close();

                        byte[] ff = FileTransferProtocol.GetFrameFileSendFinish();
                        serialPort1.Write(ff, 0, ff.Length);
                    }
                    catch (Exception er)
                    {
                        Trace.TraceError(er.Message);
                    }

                    MessageBox.Show("OK");
                })).Start();
            }
            catch (Exception er)
            {
                this.txtData.Text += er.Message;
            }
        }
コード例 #20
0
        public void init()
        {
            try
            {
                //se inicializa la configuración
                configuration = new Configuration();
                configuration.NetData.OpSystem = NetLayer.OpSystemType.WINMOBILE5POCKETPC;

                //Configuración de controles
                statusControl.connectNotification    += connect;
                statusControl.disConnectNotification += disconnect;
                chatControl.NetUser = configuration.NetUser;

                //Configuración de subprotocolos
                SubProtocolList subProtocols = new SubProtocolList();
                chatProtocol = new ChatProtocol(chatControl);
                subProtocols.add(SubProtocol.Chat.Types.CHATPROTOCOL, chatProtocol);
                fileTransferProtocol = new FileTransferProtocol(fileControl, fileListControl, createFileData());
                subProtocols.add(SubProtocol.FileTransfer.Types.FILETRANSFERPROTOCOL, fileTransferProtocol);
                pingProtocol = new PingProtocol(this);
                subProtocols.add(SubProtocol.Ping.Types.PINGPROTOCOL, pingProtocol);

                chatControl.ChatProtocol             = chatProtocol;
                fileListControl.FileTransferProtocol = fileTransferProtocol;

                //se crea el objeto de comunicación
                communication = new Communication(configuration, subProtocols, null);

                //Se setean los handlers de los eventos de usuarios
                communication.addUserEvent          += netUserControl.addUserHandler;
                communication.addUserEvent          += fileTransferProtocol.sendFileListRequest;
                communication.refreshUserEvent      += netUserControl.refreshUserHandler;
                communication.refreshLocalUserEvent += netUserControl.refreshLocalUserHandler;
                communication.removeUserEvent       += netUserControl.removeUserHandler;
                communication.removeUserEvent       += fileListControl.removeFileList;

                //Se setean los handlers de los eventos de conexion
                communication.connectEvent       += statusControl.connectHandler;
                communication.connectEvent       += fileTransferProtocol.start;
                communication.connectingEvent    += statusControl.connectingHandler;
                communication.disconnectEvent    += statusControl.disconnectHandler;
                communication.disconnectEvent    += fileTransferProtocol.stop;
                communication.disconnectEvent    += clear;
                communication.disconnectingEvent += statusControl.disconnectingHandler;
                communication.reconnectingEvent  += statusControl.reconnectingHandler;
                communication.reconnectingEvent  += fileTransferProtocol.stop;
                communication.reconnectingEvent  += clear;

                //se setean los handlers de los eventos del sistema
                communication.exceptionEvent      += exceptionHandler;
                communication.netInformationEvent += log;

                //iniciamos el consumidor de eventos
                communication.startEventConsumer();
            }
            catch (Exception e)
            {
                MessageBox.Show("Ups!: " + e.Message);
                Close();
            }
        }
コード例 #21
0
ファイル: Form1.cs プロジェクト: yanzisoft/COMFTP
        /// <summary>
        /// 使用网络向外部发文件数据
        /// </summary>
        /// <param name="stream">网络数据流对象</param>
        /// <param name="rootdir">上传起始目录</param>
        /// <param name="filenamelist">文件列表(含相对路径)</param>
        /// <param name="MN">数采仪MN</param>
        /// <param name="limited">最大允许传输率</param>
        private void SendFileToNet(NetworkStream stream, string rootdir, List <string> filenamelist, string MN, int limited)
        {
            FileStream fs = null;

            try
            {
                foreach (string filename in filenamelist)
                {
                    AddItemToList(listBoxLog, string.Format("{0} 准备传送{1}文件给数采仪:{2}", DateTime.Now.ToString(), rootdir + filename, MN));
                    fs = File.Open(rootdir + filename.ToString(), FileMode.Open, FileAccess.Read, FileShare.Read);

                    AddItemToList(listBoxLog, string.Format("数采仪:{1} 文件长度:{0}", fs.Length, MN));
                    byte[] fi = FileTransferProtocol.GetFrameFileInfo((int)fs.Length, filename.ToString());//System.IO.Path.GetFileName()
                    //AddItemToList(listBoxLog,string.Format("帧数据{0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2} {0:X2}", fi[0], fi[1], fi[2], fi[3], fi[4], fi[5], fi[6], fi[7], fi[8], fi[9], fi[10], fi[11], fi[12], fi[13], fi[14], fi[15]));
                    stream.Write(fi, 0, fi.Length);

                    int bufferSize = FileTransferProtocol.MaxFrameLength - FileTransferProtocol.FrameStructLength;
                    if (limited > 0)
                    {
                        bufferSize = limited / 10;//除以10表示由bit/s转为Byte/s
                    }
                    Byte[] bytes = new Byte[bufferSize];
                    //byte[] bytes = new byte[] { 0x30, 0x31, 0x32, 0x39 ,0x00 };


                    int    fullTime = (int)(fs.Length / (long)bufferSize);
                    int    mod      = (int)(fs.Length % (long)bufferSize);
                    Byte[] modBytes = new Byte[mod];
                    AddItemToList(listBoxLog, string.Format("数采仪:{3} 分块:{0}*{1},尾块:{2}", bufferSize, fullTime, mod, MN));

                    for (int i = 0; i < fullTime; i++)
                    {
                        int rBytes = fs.Read(bytes, 0, bufferSize);
                        AddItemToList(listBoxLog, string.Format("正在传送第{0}块给数采仪:{1}", i + 1, MN));
                        //byte[] data = FileTransferProtocol.GetFrameFileData(i * bufferSize, bytes);
                        byte[] data = FileTransferProtocol.GetFrameFileData(i + 1, bytes);
                        stream.Write(data, 0, data.Length);
                    }
                    if (mod != 0)
                    {
                        int rBytes = fs.Read(modBytes, 0, mod);
                        AddItemToList(listBoxLog, string.Format("正在传送尾块给数采仪:{0}", MN));
                        //byte[] data = FileTransferProtocol.GetFrameFileData(fullTime * bufferSize, modBytes);
                        byte[] data = FileTransferProtocol.GetFrameFileData(-1, modBytes);
                        stream.Write(data, 0, data.Length);
                    }

                    byte[] ff = FileTransferProtocol.GetFrameFileSendFinish();

                    stream.Write(ff, 0, ff.Length);
                    fs.Close();
                    fs = null;
                    AddItemToList(listBoxLog, string.Format("{0} {1} 给数采仪:{2}文件传送完毕。", DateTime.Now.ToString(), filename, MN));
                }
            }
            catch (Exception er)
            {
                AddItemToList(listBoxLog, string.Format("数采仪:{0} {1} {2}", MN, er.Source, er.Message));
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
コード例 #22
0
ファイル: Form1.cs プロジェクト: yanzisoft/COMFTP
        private void btnStart_Click(object sender, EventArgs e)
        {
            //开启服务
            if (mUpdateServiceThread == null)
            {
                mUpdateServiceThread = new Thread(delegate(object obj)
                {
                    try
                    {
                        //EventLog eventLog = new EventLog(Application.ProductName , ".", "DebugSource");

                        //eventLog.Source = "DebugSource";

                        object[] ipPortRootdirFilenamelist = (object[])obj;
                        // Set the TcpListener on port .
                        IPAddress localAddr = IPAddress.Parse(ipPortRootdirFilenamelist[0].ToString());
                        Int32 port          = int.Parse(ipPortRootdirFilenamelist[1].ToString());
                        //string rootdir = (string)ipPortRootdirFilenamelist[2];
                        //ListBox.ObjectCollection Items = (ListBox.ObjectCollection)ipPortRootdirFilenamelist[3];

                        // TcpListener server = new TcpListener(port);
                        server = new TcpListener(localAddr, port);

                        // Start listening for client requests.
                        server.Start();

                        this.Invoke(new EventHandler(delegate(Object own, EventArgs args)
                        {
                            this.btnStart.Text = "停止服务";
                            this.btnStart.Update();
                        }));

                        // Enter the listening loop.
                        int count = 0;
                        //eventLog.WriteEntry(DateTime.Now.ToString() + " 更服务端口已开启。");
                        AddItemToList(listBoxLog, DateTime.Now.ToString() + " 更服务端口已开启。");

                        while (true)
                        {
                            //Console.Write("Waiting for a connection... ");

                            // Perform a blocking call to accept requests.
                            // You could also user server.AcceptSocket() here.
                            TcpClient client = server.AcceptTcpClient();
                            count++;
                            this.Invoke(new EventHandler(delegate(Object own, EventArgs args)
                            {
                                this.lblOnlineCount.Text = string.Format("在线客户数量:{0}", count);
                                this.lblOnlineCount.Update();
                            }));

                            //AddItemToList(listBoxLog,"在线客户端数量:" + count);
                            Thread NewClientThread = new Thread(delegate(object clientobj)
                            {
                                TcpClient tcpclient = null;
                                try
                                {
                                    object[] clientRootdirFilenamelist = (object[])clientobj;
                                    tcpclient                  = (TcpClient)clientRootdirFilenamelist[0];
                                    string rootdir             = (string)clientRootdirFilenamelist[1];
                                    List <string> filenamelist = (List <string>)clientRootdirFilenamelist[2];

                                    NetworkStream stream = tcpclient.GetStream();
                                    lock (streamList)
                                    {
                                        streamList.Add(stream);
                                    }
                                    int MaxLength = FileTransferProtocol.MaxFrameLength - FileTransferProtocol.FrameStructLength;//64*1024;0xFFFF+1;64K;
                                    Byte[] data   = new Byte[MaxLength];

                                    FrameManager fm = new FrameManager(MaxLength, tcpclient);
                                    //收到客户端发来的帧数据
                                    fm.OnReceiveFrame += new FrameManager.OnReceiveFrameHandler(delegate(FileTransferProtocol.CommandType frameType, int parameter, byte[] commandData)
                                    {
                                        //TcpClient tcpclient = (TcpClient)own;
                                        //NetworkStream stream = tcpclient.GetStream();

                                        switch (frameType)
                                        {
                                        //收到远端客户端关闭帧信号
                                        case FileTransferProtocol.CommandType.CloseSocket:
                                            if (tcpclient != null)
                                            {
                                                tcpclient.Close();
                                                Debug.WriteLine("CurrentThread:{0} 准备退出", Thread.CurrentThread.Name);
                                            }
                                            //是否继续帧分析处理
                                            return(false);

                                        //如果是对方应答服务端发送的FileTransferProtocol.CommandType.WhatIsYourMNandVersion的指令
                                        case FileTransferProtocol.CommandType.MNAndVersion:
                                            //如果在MN例表中 且 version<服务端version

                                            string MN   = System.Text.Encoding.Default.GetString(commandData, 0, FileTransferProtocol.MNLength);
                                            int limited = BitConverter.ToInt32(commandData, FileTransferProtocol.MNLength);
                                            if (parameter < int.Parse(txtVersion.Text))
                                            {
                                                if (lstMN.Items.Contains(MN))
                                                {
                                                    SendFileToNet(stream, rootdir, filenamelist, MN, limited);
                                                }
                                                else
                                                {
                                                    byte[] frame = FileTransferProtocol.GetFrameMessage(string.Format("此数采仪{0}未在可更新列表中。", MN));
                                                    stream.Write(frame, 0, frame.Length);
                                                }
                                            }
                                            else
                                            {
                                                byte[] frame = FileTransferProtocol.GetFrameMessage(string.Format("此数采仪{0}程序已经是最新版了。", MN));
                                                stream.Write(frame, 0, frame.Length);
                                            }
                                            break;
                                        }
                                        //是否继续帧分析处理
                                        Debug.WriteLine("CurrentThread:{0} 继续运行", Thread.CurrentThread.Name);
                                        return(true);
                                    });

                                    bool running = true;
                                    while (running)
                                    {
                                        Debug.WriteLine(string.Format("{0}", Thread.CurrentThread.ThreadState));

                                        Int32 bytes = stream.Read(data, 0, data.Length);
                                        if (bytes > 0)
                                        {
                                            running = fm.Handler(bytes, data);
                                        }
                                        else
                                        {
                                            //远端客户主动断开socket
                                            running = false;
                                        }
                                    }
                                }
                                catch (Exception er)
                                {
                                    //eventLog.WriteEntry(DateTime.Now.ToString() + "异常:" + er.Source + " " + er.Message);
                                    AddItemToList(listBoxLog, DateTime.Now.ToString() + "异常:" + er.Source + " " + er.Message);
                                }
                                finally
                                {
                                    tcpclient.Close();
                                }

                                lock ((object)count)
                                {
                                    count--;
                                    //AddItemToList(listBoxLog,"在线客户端数量:" + count);
                                    try
                                    {
                                        this.Invoke(new EventHandler(delegate(Object own, EventArgs args)
                                        {
                                            this.lblOnlineCount.Text = string.Format("在线客户数量:{0}", count);
                                            this.lblOnlineCount.Update();
                                        }));
                                    }
                                    catch (Exception er)
                                    {
                                    }
                                }
                            });
                            NewClientThread.Name = "读线程" + NewClientThread.ManagedThreadId;
                            threadList.Add(NewClientThread);
                            NewClientThread.Start(new object[] { client, ipPortRootdirFilenamelist[2] /*rootdir*/, ipPortRootdirFilenamelist[3] /*listBox1.Items*/ });
                            //Console.WriteLine("Connected!");
                        }
                    }
                    catch (SocketException er)
                    {
                        //Console.WriteLine("网络异常: {0}", e);
                        //MessageBox.Show(er.Message, "网络异常");

                        //如果是server.Stop()停止服务引起的则忽略错误的显示
                        if (er.SocketErrorCode == SocketError.Interrupted)
                        {
                        }
                        else
                        {
                            AddItemToList(listBoxLog, DateTime.Now.ToString() + " " + er.Source + " " + er.Message);
                        }
                    }
                    finally
                    {
                        // Stop listening for new clients.
                        server.Stop();
                    }
                });
                mUpdateServiceThread.Name = "更新程序监听主线程";
                mUpdateServiceThread.Start(new object[] { cmbIP.Text, txtPort.Text, txtRootDir.Text, fileNameList });
            }
            else//关闭服务
            {
                server.Stop();
                AbortUpdateServiceThread();
            }
        }
コード例 #23
0
        private void ConnectOrDisconnect()
        {
            var ip   = cmbIP.Text;
            var port = int.Parse(txtPort.Text);

            if (mThreadConnectToServer == null)
            {
                mThreadConnectToServer = new Thread(new ThreadStart(delegate()
                {
                    try
                    {
                        if (stream != null)
                        {
                            stream.Close();
                        }

                        tcpclient = new TcpClient(ip, port);
                        //SetButtonState(btnConnect, "断开(&S)");
                        tcpclient.ReceiveBufferSize = 0xFFFF + 1;
                        tcpclient.SendBufferSize    = 0xFFFF + 1;
                        stream = tcpclient.GetStream();
                        int revFilePartCount = 0;

                        try
                        {
                            stream.Write(System.Text.Encoding.Default.GetBytes("OK"), 0, 2);
                            SetButtonState(btnConnect, "断开(&S)");
                        }
                        catch (Exception ex)
                        {
                            if (stream != null)
                            {
                                stream.Close();
                            }
                            if (tcpclient != null)
                            {
                                tcpclient.Close();
                            }
                            mThreadConnectToServer.Abort();
                            return;
                        }

                        //创建帧分析对象
                        fFrameMgr = new FrameManager((ushort)(serialPort1.ReadBufferSize * 3), stream);
                        //实现帧处理函数
                        fFrameMgr.OnReceiveFrame += new FrameManager.OnReceiveFrameHandler(
                            delegate(/*object _stream,*/ FileTransferProtocol.CommandType frameType, int parameter, byte[] commandData)
                        {
                            //NetworkStream nStream = (NetworkStream)_stream;

                            switch (frameType)
                            {
                            case FileTransferProtocol.CommandType.FileName:
                                string fileName = System.Text.Encoding.Default.GetString(commandData, 0, commandData.Length);

                                if (fileName != null)
                                {
                                    if (fStream != null)
                                    {
                                        fStream.Close();
                                        fStream = null;
                                    }
                                    revFilePartCount   = 0;
                                    string CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
                                    string startDir    = CurrentPath + @"\update\";
                                    if (!Directory.Exists(startDir))
                                    {
                                        Directory.CreateDirectory(startDir);
                                    }

                                    if (File.Exists(startDir + fileName))
                                    {
                                        File.Delete(startDir + fileName);
                                    }
                                    fStream = File.Open(startDir + fileName, FileMode.CreateNew);

                                    AddItemToList(listBox1, DateTime.Now.ToString() + " 准备接收文件:" + fileName + " 文件总长度:" + parameter);
                                }
                                break;

                            case FileTransferProtocol.CommandType.FileData:
                                if (fStream != null && commandData != null && commandData.Length > 0)
                                {
                                    revFilePartCount++;
                                    fStream.Write(commandData, 0, commandData.Length);
                                    AddItemToList(listBox1, string.Format("收到 第{0}块 数据长度:{1} 服务器端分块号:{2} ", revFilePartCount, commandData.Length, parameter));
                                }
                                break;

                            case FileTransferProtocol.CommandType.FileSendFinish:

                                if (fStream != null)
                                {
                                    fStream.Close();
                                    fStream = null;
                                    AddItemToList(listBox1, DateTime.Now.ToString() + " 收到文件结束信号");
                                }
                                break;

                            case FileTransferProtocol.CommandType.WhatIsYourMNandVersion:
                                byte[] frame = FileTransferProtocol.GetFrameWhatIsYourMNandVersion();
                                stream.Write(frame, 0, frame.Length);
                                break;

                            case FileTransferProtocol.CommandType.Message:
                                string message = System.Text.Encoding.Default.GetString(commandData, 0, commandData.Length);

                                AddItemToList(listBox1, message);

                                break;
                            }

                            return(true);
                        });


                        //------------------------------------------------------------------------------------
                        //方式0数采仪被动更新(只有在更新服务器询问[指定列表的]数采仪时,则数据采仪才更新)
                        //------------------------------------------------------------------------------------
                        ////把 网络 或 串口 的 数据 传给 帧分析对象的Handler函数做分析
                        if (receiveThread == null)
                        {
                            receiveThread = new Thread(new ThreadStart(delegate()
                            {
                                int MaxLength = FileTransferProtocol.MaxFrameLength - FileTransferProtocol.FrameStructLength;//64*1024;0xFFFF+1;64K;
                                Byte[] data   = new Byte[MaxLength];
                                try
                                {
                                    bool running = true;
                                    while (running)
                                    {
                                        Debug.WriteLine(string.Format("{0}", Thread.CurrentThread.Name));


                                        Int32 bytes = 0;
                                        try
                                        {
                                            bytes = stream.Read(data, 0, data.Length);
                                        }
                                        catch (System.IO.IOException er)
                                        {
                                            DisConnect();
                                        }
                                        if (bytes > 0)
                                        {
                                            //这是处理收到帧
                                            running = fFrameMgr.Handler(bytes, data);
                                        }
                                        else
                                        {
                                            //远端客户主动断开socket
                                            running = false;
                                        }
                                    }
                                }
                                catch (ThreadAbortException er)
                                {
                                    AddItemToList(listBox1, string.Format(DateTime.Now.ToString() + " 连接{0}:{1}未成功或已取消", ip, port));
                                    receiveThread = null;
                                }
                                catch (Exception err)
                                {
                                    AddItemToList(listBox1, DateTime.Now.ToString() + " " + err.Message);
                                }
                            }));
                            receiveThread.Start();
                        }
                        else
                        {
                            if (stream != null)
                            {
                                stream.Close();
                            }
                            receiveThread.Abort();
                            receiveThread = null;
                        }
                        //-----------------------------------------方式0--------------------------------------
                    }
                    catch (ThreadAbortException er)
                    {
                        AddItemToList(listBox1, string.Format(DateTime.Now.ToString() + " 连接{0}:{1}未成功或已取消", ip, port));
                        mThreadConnectToServer = null;
                    }
                    catch (SocketException er)
                    {
                        AddItemToList(listBox1, DateTime.Now.ToString() + " " + er.Message);
                        DisConnect();
                    }
                }));
                mThreadConnectToServer.Start();
            }
            else
            {
                DisConnect();
            }
        }
コード例 #24
0
        //FileStream fStream = null;
        private void SetupFrameHandler()
        {
            serialPortFrameMgr = new FrameManager((ushort)(serialPort1.ReadBufferSize * 3), serialPort1);

            serialPortFrameMgr.OnReceiveFrame += new FrameManager.OnReceiveFrameHandler(
                delegate(/*object own,*/ FileTransferProtocol.CommandType frameType, int parameter, byte[] commandData)
            {
                //SerialPort serialPort = (SerialPort)own;

                switch (frameType)
                {
                case FileTransferProtocol.CommandType.FileName:
                    string fileName = System.Text.Encoding.Default.GetString(commandData, 0, commandData.Length);

                    if (fileName != null)
                    {
                        if (fStream != null)
                        {
                            fStream.Close();
                            fStream = null;
                        }
                        string CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
                        string startDir    = CurrentPath + @"\update\";
                        if (!Directory.Exists(startDir))
                        {
                            Directory.CreateDirectory(startDir);
                        }
                        if (File.Exists(startDir + fileName))
                        {
                            File.Delete(startDir + fileName);
                        }
                        fStream = File.Open(startDir + fileName, FileMode.CreateNew);

                        SetText(DateTime.Now.ToString() + " 准备接收文件:" + fileName + " 文件总长度:" + parameter);
                    }
                    break;

                case FileTransferProtocol.CommandType.FileData:
                    if (fStream != null && commandData != null && commandData.Length > 0)
                    {
                        fStream.Write(commandData, 0, commandData.Length);
                        SetText("收到文件数据长度" + commandData.Length);
                    }
                    break;

                case FileTransferProtocol.CommandType.FileSendFinish:

                    if (fStream != null)
                    {
                        fStream.Close();
                        fStream = null;
                        SetText(DateTime.Now.ToString() + " 收到文件结束信号");
                    }
                    break;

                case FileTransferProtocol.CommandType.WhatIsYourMNandVersion:
                    //byte[] frame = FileTransferProtocol.GetFrameMNAndVersion(1, "456");
                    byte[] frame = FileTransferProtocol.GetFrameWhatIsYourMNandVersion();
                    serialPort1.Write(frame, 0, frame.Length);
                    break;

                case FileTransferProtocol.CommandType.Message:
                    string message = System.Text.Encoding.Default.GetString(commandData, 0, commandData.Length);
                    this.Invoke(new EventHandler(delegate(object s, EventArgs ar)
                    {
                        this.txtData.Text += message + "\r\n";
                    }));
                    break;
                }

                return(true);
            });
        }
コード例 #25
0
        public void init()
        {
            try
            {
                //incializamos una configuracion
                configuration = new Configuration();

                //OS
                configuration.NetData.OpSystem = OpSystemType.WIN7;

                //configuramos los controles
                statusControl.connectNotification    += connect;
                statusControl.disConnectNotification += disconnect;
                chatControl.NetUser = configuration.NetUser;

                //configuramos los sub protocolos
                SubProtocolList subProtocols = new SubProtocolList();
                chatProtocol = new ChatProtocol(chatControl);
                subProtocols.add(SubProtocol.Chat.Types.CHATPROTOCOL, chatProtocol);
                fileTransferProtocol = new FileTransferProtocol(fileControl, fileListControl, createFileData());
                subProtocols.add(SubProtocol.FileTransfer.Types.FILETRANSFERPROTOCOL, fileTransferProtocol);
                pingProtocol = new PingProtocol(this);
                subProtocols.add(SubProtocol.Ping.Types.PINGPROTOCOL, pingProtocol);

                chatControl.ChatProtocol             = chatProtocol;
                fileListControl.FileTransferProtocol = fileTransferProtocol;

                //Configuramos los tipos de mensajes que no pertenecen a subprotocolos
                MessageTypeList messageTypeList = new MessageTypeList();

                //se crea el objeto de comunicación
                communication = new Communication(configuration, subProtocols, messageTypeList);

                //Se setean los handlers de los eventos de usuarios
                communication.addUserEvent          += netUserControl.addUserHandler;
                communication.addUserEvent          += fileTransferProtocol.sendFileListRequest;
                communication.addUserEvent          += networkGraphControl.addUserHandler;
                communication.refreshUserEvent      += netUserControl.refreshUserHandler;
                communication.refreshUserEvent      += networkGraphControl.refreshUserHandler;
                communication.refreshLocalUserEvent += netUserControl.refreshLocalUserHandler;
                communication.refreshLocalUserEvent += networkGraphControl.refreshLocalUserHandler;
                communication.removeUserEvent       += netUserControl.removeUserHandler;
                communication.removeUserEvent       += fileListControl.removeFileList;
                communication.removeUserEvent       += networkGraphControl.removeUserHandler;

                //Se setean los handlers de los eventos de conexion
                communication.connectEvent       += statusControl.connectHandler;
                communication.connectEvent       += fileTransferProtocol.start;
                communication.connectingEvent    += statusControl.connectingHandler;
                communication.disconnectEvent    += statusControl.disconnectHandler;
                communication.disconnectEvent    += fileTransferProtocol.stop;
                communication.disconnectEvent    += clear;
                communication.disconnectingEvent += statusControl.disconnectingHandler;
                communication.reconnectingEvent  += statusControl.reconnectingHandler;
                communication.reconnectingEvent  += fileTransferProtocol.stop;
                communication.reconnectingEvent  += clear;

                //Se setean los handlers de los eventos del sistems
                communication.exceptionEvent      += exceptionHandler;
                communication.netInformationEvent += netInformationHandler;

                //iniciamos el consumidor de eventos
                communication.startEventConsumer();

                //Se abre el archivo para log
                FileInfo t = new FileInfo("CommLayer.log");
                Tex = t.AppendText();
            }
            catch (Exception e)
            {
                MessageBox.Show("Ups!: " + e.Message);
                Close();
            }
        }