コード例 #1
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);
        }
コード例 #2
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();
            }
        }