private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { int count = serialPort1.BytesToRead; //MessageBox.Show("count:"+count); byte[] tmp = new byte[count]; serialPort1.Read(tmp, 0, count); serialPortFrameMgr.Handler(count, tmp); }
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { int count = serialPort1.BytesToRead; //MessageBox.Show("count:" + count); //Debug.WriteLine("count:" + count); byte[] tmp = new byte[count]; serialPort1.Read(tmp, 0, count); //for (int i = 0; i < count; i++) //{ // SetText(string.Format("{0:X2} ", tmp[i])); //} serialPortFrameMgr.Handler(count, tmp); }
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(); } }
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(); } }