TCPServer多线程发送

using System; 

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;
using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Threading;

using System.Net.Sockets;

using System.Net;

namespace TCPServer { public partial class Form1 : Form { Thread threadWatch = null; // 负责监听客户端连接请求的 线程; Socket socketWatch = null;//服务器套接字 Thread MonitoThread = null;//服务器监控客户端连接情况的线程 //客户ip 存放套接字 Dictionary<string, Socket> dict = new Dictionary<string, Socket>(); //存放线程 Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>(); public Form1() { //有时候会遇到窗体间的控件访问异常,需要这样处理 Control.CheckForIllegalCrossThreadCalls=false; InitializeComponent(); cbx_Select.SelectedIndex = 0; } //监听 private void Connect_Click(object sender, EventArgs e) { // 创建负责监听的套接字,注意其中的参数; socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 获得文本框中的IP对象; IPAddress address = IPAddress.Parse(cbx_IP.Text.Trim()); // 创建包含ip和端口号的网络节点对象; IPEndPoint endPoint = new IPEndPoint(address, int.Parse(tbxPort.Text.Trim())); try { // 将负责监听的套接字绑定到唯一的ip和端口上; socketWatch.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); socketWatch.Bind(endPoint); } catch (SocketException se) { MessageBox.Show("异常:" + se.Message); return; } // 设置监听队列的长度; socketWatch.Listen(10000); // 创建负责监听的线程; threadWatch = new Thread(WatchConnecting); threadWatch.IsBackground = true; threadWatch.Start(); messageDelegate.Messages(tbx_Show, "服务器启动监听成功!"); } /// /// 监听客户端请求的方法; /// void WatchConnecting() { messageDelegate.Messages(tbx_Show, "新客户端连接成功!"); while (true) // 持续不断的监听客户端的连接请求; { // 开始监听客户端连接请求,Accept方法会阻断当前的线程; Socket sokConnection = socketWatch.Accept(); // 一旦监听到一个客户端的请求,就返回一个与该客户端通信的 套接字; var ssss = sokConnection.RemoteEndPoint.ToString().Split(':');//192.168.20.181:51566 //查找ListBox集合中是否包含此IP开头的项,找到为0,找不到为-1 if (lbOnline.FindString(ssss[0]) >= 0) { lbOnline.Items.Remove(sokConnection.RemoteEndPoint.ToString()); } else { lbOnline.Items.Add(sokConnection.RemoteEndPoint.ToString()); //F0AAAAAAAAAAAAF1080082001900000000FE byte[] data = new byte[] { 0xF0, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xF1, 0x08, 0x00, 0x82, 0x00, 0x19, 0x00, 0x00, 0x00, 0x00, 0xFE }; sokConnection.Send(data); messageDelegate.Messages(tbx_Show, "服务器向客户端" + sokConnection.RemoteEndPoint.ToString() + "发送:" + BitConverter.ToString(data).Replace("-", "") + "\r\n"); } // 将与客户端连接的 套接字 对象添加到集合中; dict.Add(sokConnection.RemoteEndPoint.ToString(), sokConnection); Thread thr = new Thread(RecMsg); thr.IsBackground = true; thr.Start(sokConnection); dictThread.Add(sokConnection.RemoteEndPoint.ToString(), thr); // 将新建的线程 添加 到线程的集合中去。 } } void RecMsg(object sokConnectionparn) { Socket sokClient = sokConnectionparn as Socket; while (true) { // 定义一个缓存区; byte[] arrMsgRec = new byte[1024]; // 将接受到的数据存入到输入 arrMsgRec中; int bytesRead = -1; string strshow=null; try { //定义一个1M的内存缓冲区,用于临时性存储接收到的消息 byte[] arrRecvmsg = new byte[1024 * 1024 * 2]; //将客户端套接字接收到的数据存入内存缓冲区,并获取长度 bytesRead = sokClient.Receive(arrRecvmsg, arrRecvmsg.Length, 0); // 接收数据,并返回数据的长度; if (bytesRead > 0) { byte[] data = new byte[bytesRead]; for (int j = 0; j < bytesRead; j++) { data[j] = arrRecvmsg[j]; strshow += data[j].ToString("X2"); } if (data.Length == 40 && data[8].ToString("X") == "1E" && data[9] == 0 && data[10].ToString("X") == "43" && data[11] == 0 && data[14] == 0) { byte[] showaddr = new byte[] { (byte)data[15], (byte)data[16], (byte)data[17], (byte)data[18], (byte)data[19], (byte)data[20] }; tbx_ID.Text = BitConverter.ToString(showaddr).Replace("-",""); } //主业务 messageDelegate.Messages(tbx_Show, DateTime.Now+" " +sokClient.RemoteEndPoint.ToString()+ "接收数据:" + strshow.Replace("-", "")); } else { // 从 通信套接字 集合中删除被中断连接的通信套接字; dict.Remove(sokClient.RemoteEndPoint.ToString()); // 从通信线程集合中删除被中断连接的通信线程对象; dictThread.Remove(sokClient.RemoteEndPoint.ToString()); // 从列表中移除被中断的连接IP lbOnline.Items.Remove(sokClient.RemoteEndPoint.ToString()); messageDelegate.Messages(tbx_Show, DateTime.Now+"" + sokClient.RemoteEndPoint.ToString() + "断开连接\r\n"); //log.log("遇见异常"+se.Message); break; } } catch (SocketException se) { // 从 通信套接字 集合中删除被中断连接的通信套接字; dict.Remove(sokClient.RemoteEndPoint.ToString()); // 从通信线程集合中删除被中断连接的通信线程对象; dictThread.Remove(sokClient.RemoteEndPoint.ToString()); // 从列表中移除被中断的连接IP lbOnline.Items.Remove(sokClient.RemoteEndPoint.ToString()); messageDelegate.Messages(tbx_Show, DateTime.Now + "" + sokClient.RemoteEndPoint.ToString() + "断开,异常消息:" + se.Message + "\r\n"); //log.log("遇见异常"+se.Message); break; } catch (Exception e) { // 从 通信套接字 集合中删除被中断连接的通信套接字; dict.Remove(sokClient.RemoteEndPoint.ToString()); // 从通信线程集合中删除被中断连接的通信线程对象; dictThread.Remove(sokClient.RemoteEndPoint.ToString()); // 从列表中移除被中断的连接IP lbOnline.Items.Remove(sokClient.RemoteEndPoint.ToString()); messageDelegate.Messages(tbx_Show, DateTime.Now + "异常消息:" + e.Message + "\r\n"); // log.log("遇见异常" + e.Message); break; } } } private void Form1_Load(object sender, EventArgs e) { //获取本地的IP地址 string AddressIP = string.Empty; List array=new List(); foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (_IPAddress.AddressFamily.ToString() == "InterNetwork") { AddressIP = _IPAddress.ToString(); array.Add(AddressIP); } } //给IP控件赋值 cbx_IP.DataSource=array; } //设置集中器IP private void btn_Set_Click(object sender, EventArgs e) { if (lbOnline.Items.Count!= 0) { if (lbOnline.SelectedIndex == -1) { //MessageBox.Show("请选中要设置的集中器的IP","Error"); lbOnline.SelectedIndex = 0; #region if (tbx_DNS.Enabled == true) { if (tbx_IP.Text != null || tbx_Select.Text != null || tbx_DNS.Text != null) { string[] values = new string[dictThread.Count]; byte[] SendData = SetServerIP.ServerIP(lbOnline, tbx_IP, tbx_Net, tbx_Isnet, tbx_Select, tbx_DNS); foreach (var client in dict) { //新建一条线程发送数据到客户端 newOneThreadSendDataToClient(client.Value, SendData, SendData.Length); // messageDelegate.Messages(tbx_Show, DateTime.Now + "异常消息:" + key + "\r\n"); } } else { MessageBox.Show("请查看集中器IP或服务器域名或DNS是否为空!", "Error"); } } #endregion else { if (tbx_IP.Text != null || tbx_Select.Text != null) { string[] values = new string[dictThread.Count]; byte[] SendData = SetServerIP.ServerIP(lbOnline, tbx_IP, tbx_Net, tbx_Isnet, tbx_Select); foreach (var client in dict) { //新建一条线程发送数据到客户端 newOneThreadSendDataToClient(client.Value, SendData, SendData.Length); // messageDelegate.Messages(tbx_Show, DateTime.Now + "异常消息:" + key + "\r\n"); } ////遍历value //foreach (Thread value in dictThread.Values) //{ // messageDelegate.Messages(tbx_Show, DateTime.Now + "异常消息:" + value + "\r\n"); //} } else { MessageBox.Show("请查看集中器IP或服务器IP是否为空!", "Error"); } } } } else { MessageBox.Show("请先连入客户端!","ERROR"); } } void newOneThreadSendDataToClient(Socket clientSocket, byte[] datas, int length) { //跨线程显示提示消息 messageDelegate.Messages(tbx_Show, DateTime.Now + "新建一条线程准备开始发送数据"); //新建发送数据的参数模型 dataSendArgsMode sendDataArgs = new dataSendArgsMode(); //将客户端套接字绑定到模型 sendDataArgs.sockets = clientSocket; //将数据绑定到模型 sendDataArgs.datas = datas; //将数据长度绑定到模型 sendDataArgs.length = length; //新建发送数据到客户端的线程 Thread threadSendDataToClient = new Thread(sendDataToClient); //后台运行线程 threadSendDataToClient.IsBackground = true; //启动线程,并将 发送数据的参数模型 绑定到线程执行的方法 threadSendDataToClient.Start(sendDataArgs); } /// /// 发送数据到客户端 /// ///void sendDataToClient(object obj) { //获取用于发送数据的参数模型 dataSendArgsMode args = obj as dataSendArgsMode; try { //从数据参数模型中提取数据发送到模型中的客户端 args.sockets.Send(args.datas, 0, args.length, SocketFlags.None); //跨线程显示提示消息 messageDelegate.Messages(tbx_Show, DateTime.Now + "数据:" + getStringFormByte(args.datas, args.length) + "发送到了客户端:" + args.sockets.RemoteEndPoint.ToString()); messageDelegate.Messages(tbx_Show, DateTime.Now + "数据发送完毕,关闭线程"); //释放该线程 return; } catch { //从集合中移除客户端套接字 dict.Remove(args.sockets.RemoteEndPoint.ToString()); //从集合中移除客户端线程 dictThread.Remove(args.sockets.RemoteEndPoint.ToString()); //从列表中移除客户端套接字的远程终结点 //deleteClientSocket(args.sockets.RemoteEndPoint.ToString()); //跨线程显示提示消息 messageDelegate.Messages(tbx_Show, DateTime.Now + "异常:" + "客户端" + args.sockets.RemoteEndPoint.ToString() + "断开连接" + ",关闭该线程"); //释放该线程 return; } } /// /// 16进制的字符串形式 /// ///////// string getStringFormByte(byte[] data, int length) { string str = ""; for (int i = 0; i < length; i++) { str += data[i].ToString("X").PadLeft(2, '0') + ' '; } return str; } //刷新 private void t_Refurbish_Tick(object sender, EventArgs e) { if (cbx_Select.SelectedIndex == 0) { tbx_DNS.Enabled = false; label5.Enabled = false; } else if (cbx_Select.SelectedIndex == 1) { tbx_DNS.Enabled = true; label5.Enabled = true; } } } } namespace TCPServer { partial class Form1 { /// /// 必需的设计器变量。 /// private System.ComponentModel.IContainer components = null; /// /// 清理所有正在使用的资源。 /// ///如果应释放托管资源,为 true;否则为 false。 protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.tbxPort = new System.Windows.Forms.TextBox(); this.Connect = new System.Windows.Forms.Button(); this.tbx_Show = new System.Windows.Forms.TextBox(); this.lbOnline = new System.Windows.Forms.ListBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.cbx_IP = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.tbx_IP = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.tbx_Addr = new System.Windows.Forms.TextBox(); this.btn_Set = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.label5 = new System.Windows.Forms.Label(); this.tbx_DNS = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.tbx_ID = new System.Windows.Forms.TextBox(); this.cbx_Select = new System.Windows.Forms.ComboBox(); this.tbx_Select = new System.Windows.Forms.TextBox(); this.t_Refurbish = new System.Windows.Forms.Timer(this.components); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label6 = new System.Windows.Forms.Label(); this.tbx_Isnet = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.tbx_Net = new System.Windows.Forms.TextBox(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // tbxPort // this.tbxPort.Location = new System.Drawing.Point(246, 7); this.tbxPort.Name = "tbxPort"; this.tbxPort.Size = new System.Drawing.Size(100, 21); this.tbxPort.TabIndex = 19; this.tbxPort.Text = "1235"; // // Connect // this.Connect.Location = new System.Drawing.Point(352, 6); this.Connect.Name = "Connect"; this.Connect.Size = new System.Drawing.Size(75, 23); this.Connect.TabIndex = 18; this.Connect.Text = "监听"; this.Connect.UseVisualStyleBackColor = true; this.Connect.Click += new System.EventHandler(this.Connect_Click); // // tbx_Show // this.tbx_Show.Location = new System.Drawing.Point(184, 334); this.tbx_Show.Multiline = true; this.tbx_Show.Name = "tbx_Show"; this.tbx_Show.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.tbx_Show.Size = new System.Drawing.Size(725, 211); this.tbx_Show.TabIndex = 20; // // lbOnline // this.lbOnline.Dock = System.Windows.Forms.DockStyle.Fill; this.lbOnline.FormattingEnabled = true; this.lbOnline.ItemHeight = 12; this.lbOnline.Location = new System.Drawing.Point(3, 17); this.lbOnline.Name = "lbOnline"; this.lbOnline.ScrollAlwaysVisible = true; this.lbOnline.Size = new System.Drawing.Size(175, 496); this.lbOnline.TabIndex = 22; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 11); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(59, 12); this.label1.TabIndex = 23; this.label1.Text = "服务器IP:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(199, 11); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(29, 12); this.label2.TabIndex = 24; this.label2.Text = "端口"; // // cbx_IP // this.cbx_IP.FormattingEnabled = true; this.cbx_IP.Location = new System.Drawing.Point(66, 7); this.cbx_IP.Name = "cbx_IP"; this.cbx_IP.Size = new System.Drawing.Size(121, 20); this.cbx_IP.TabIndex = 25; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(211, 104); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(53, 12); this.label3.TabIndex = 27; this.label3.Text = "集中器IP"; // // tbx_IP // this.tbx_IP.Location = new System.Drawing.Point(287, 100); this.tbx_IP.Name = "tbx_IP"; this.tbx_IP.Size = new System.Drawing.Size(136, 21); this.tbx_IP.TabIndex = 26; this.tbx_IP.Text = "192.168.20.25"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(183, 290); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(65, 12); this.label4.TabIndex = 29; this.label4.Text = "集中器地址"; this.label4.Visible = false; // // tbx_Addr // this.tbx_Addr.Location = new System.Drawing.Point(282, 287); this.tbx_Addr.Name = "tbx_Addr"; this.tbx_Addr.Size = new System.Drawing.Size(100, 21); this.tbx_Addr.TabIndex = 28; this.tbx_Addr.Visible = false; // // btn_Set // this.btn_Set.Location = new System.Drawing.Point(456, 131); this.btn_Set.Name = "btn_Set"; this.btn_Set.Size = new System.Drawing.Size(75, 23); this.btn_Set.TabIndex = 30; this.btn_Set.Text = "设置"; this.btn_Set.UseVisualStyleBackColor = true; this.btn_Set.Click += new System.EventHandler(this.btn_Set_Click); // // button1 // this.button1.Location = new System.Drawing.Point(414, 285); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 31; this.button1.Text = "设置"; this.button1.UseVisualStyleBackColor = true; this.button1.Visible = false; // // label5 // this.label5.AutoSize = true; this.label5.Enabled = false; this.label5.Location = new System.Drawing.Point(211, 239); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(23, 12); this.label5.TabIndex = 33; this.label5.Text = "DNS"; // // tbx_DNS // this.tbx_DNS.Enabled = false; this.tbx_DNS.Location = new System.Drawing.Point(287, 232); this.tbx_DNS.Name = "tbx_DNS"; this.tbx_DNS.Size = new System.Drawing.Size(136, 21); this.tbx_DNS.TabIndex = 32; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(211, 73); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(53, 12); this.label7.TabIndex = 37; this.label7.Text = "集中器ID"; // // tbx_ID // this.tbx_ID.Location = new System.Drawing.Point(287, 67); this.tbx_ID.Name = "tbx_ID"; this.tbx_ID.ReadOnly = true; this.tbx_ID.Size = new System.Drawing.Size(136, 21); this.tbx_ID.TabIndex = 36; // // cbx_Select // this.cbx_Select.BackColor = System.Drawing.SystemColors.Window; this.cbx_Select.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbx_Select.FormattingEnabled = true; this.cbx_Select.Items.AddRange(new object[] { "服务器IP", "服务器域名"}); this.cbx_Select.Location = new System.Drawing.Point(190, 199); this.cbx_Select.Name = "cbx_Select"; this.cbx_Select.Size = new System.Drawing.Size(86, 20); this.cbx_Select.TabIndex = 38; // // tbx_Select // this.tbx_Select.Location = new System.Drawing.Point(287, 199); this.tbx_Select.Name = "tbx_Select"; this.tbx_Select.Size = new System.Drawing.Size(136, 21); this.tbx_Select.TabIndex = 39; this.tbx_Select.Text = "192.168.20.15"; // // t_Refurbish // this.t_Refurbish.Enabled = true; this.t_Refurbish.Interval = 1000; this.t_Refurbish.Tick += new System.EventHandler(this.t_Refurbish_Tick); // // groupBox1 // this.groupBox1.Controls.Add(this.lbOnline); this.groupBox1.Location = new System.Drawing.Point(1, 29); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(181, 516); this.groupBox1.TabIndex = 40; this.groupBox1.TabStop = false; this.groupBox1.Text = "连接的集中器IP"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(211, 138); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(53, 12); this.label6.TabIndex = 42; this.label6.Text = "子网掩码"; // // tbx_Isnet // this.tbx_Isnet.Location = new System.Drawing.Point(287, 133); this.tbx_Isnet.Name = "tbx_Isnet"; this.tbx_Isnet.Size = new System.Drawing.Size(136, 21); this.tbx_Isnet.TabIndex = 41; this.tbx_Isnet.Text = "255.255.255.0"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(214, 171); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(29, 12); this.label8.TabIndex = 44; this.label8.Text = "网关"; // // tbx_Net // this.tbx_Net.Location = new System.Drawing.Point(287, 166); this.tbx_Net.Name = "tbx_Net"; this.tbx_Net.Size = new System.Drawing.Size(136, 21); this.tbx_Net.TabIndex = 43; this.tbx_Net.Text = "192.168.20.1"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(907, 547); this.Controls.Add(this.label8); this.Controls.Add(this.tbx_Net); this.Controls.Add(this.label6); this.Controls.Add(this.tbx_Isnet); this.Controls.Add(this.groupBox1); this.Controls.Add(this.tbx_Select); this.Controls.Add(this.cbx_Select); this.Controls.Add(this.label7); this.Controls.Add(this.tbx_ID); this.Controls.Add(this.label5); this.Controls.Add(this.tbx_DNS); this.Controls.Add(this.button1); this.Controls.Add(this.btn_Set); this.Controls.Add(this.label4); this.Controls.Add(this.tbx_Addr); this.Controls.Add(this.label3); this.Controls.Add(this.tbx_IP); this.Controls.Add(this.cbx_IP); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.tbx_Show); this.Controls.Add(this.tbxPort); this.Controls.Add(this.Connect); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox tbxPort; private System.Windows.Forms.Button Connect; private System.Windows.Forms.TextBox tbx_Show; private System.Windows.Forms.ListBox lbOnline; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cbx_IP; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox tbx_IP; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox tbx_Addr; private System.Windows.Forms.Button btn_Set; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox tbx_DNS; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox tbx_ID; private System.Windows.Forms.ComboBox cbx_Select; private System.Windows.Forms.TextBox tbx_Select; private System.Windows.Forms.Timer t_Refurbish; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox tbx_Isnet; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox tbx_Net; } } using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; namespace TCPServer { /// /// 发送数据的参数 /// class dataSendArgsMode { /// /// 套接字 /// public Socket sockets; /// /// 数据 /// public byte[] datas; /// /// 长度 /// public int length; } } using System; using System.Collections.Generic; using System.Text; namespace TCPServer { public class BytesConvert { /// /// 字节数组逆转 /// ////// public static byte[] bytesConvert(byte[] s) { byte[] byteNew = new byte[s.Length]; for (int i = s.Length - 1; i >= 0; i--) { byteNew[s.Length - i - 1] = s[i]; } //byte[] temp = new byte[2]; //temp[0] = s[1]; //temp[1] = s[0]; return byteNew; } } } using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Net; namespace TCPServer { class IPConvertBytes { public static byte[] ipAddrToBytes(TextBox tbxip) { byte[] bytes = null; string str=tbxip.Text.ToString(); Match ipRegex = Regex.Match(tbxip.ToString().Trim(), @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}"); if (ipRegex.Success) { //IP地址压缩成4字节,如果要进一步处理的话,就可以转换成一个int了. IPAddress address = IPAddress.Parse(tbxip.Text.Trim()); bytes=address.GetAddressBytes(); //var strs = tbxip.Text.Split('.'); ////bytes[0] = Convert.ToByte(strs[0], 16); //for (int i = 0; i < str.Length; i++) //{ // int m = Convert.ToInt32(strs[i]); // bytes[i] = Convert.ToByte(m.ToString("X"), 16); //} return bytes; } else { List lbyte = new List(); char[] values = str.ToCharArray(); foreach (char letter in values) { // Get the integral value of the character. byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(letter.ToString()); lbyte.AddRange(byteArray); } byte[] result = new byte[lbyte.Count]; lbyte.CopyTo(result); return result; } } } } using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace TCPServer { public class messageDelegate { public delegate void MessageDelegate(TextBox txtbox, string Messages);//委托文本框 //文本框Invoke方法需要创建一个委托。你可以事先写好函数和与之对应的委托 public static void Messages(TextBox txtbox, string message) { if (txtbox.InvokeRequired)//示调用方在对控件进行方法调用时是否必须调用 Invoke 方法,因为调用方位于创建控件所在的线程以外的线程中。 { MessageDelegate showMessageDelegate = Messages; txtbox.Invoke(showMessageDelegate, new object[] { txtbox, message }); } else { txtbox.Text += message + "\r\n"; txtbox.SelectionStart = txtbox.Text.Length; txtbox.SelectionLength = 0; txtbox.ScrollToCaret(); } } } } using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Net; namespace TCPServer { class SetServerIP { //选中要设置的集中器IP private static IPEndPoint iep; /// /// /// ///传入IP、端口 ///传入要设置的集中器的IP ///传入要设置的集中器的子网掩码 ///传入要设置的集中器的网关 ///传入要连接的服务器的IP public static byte[] ServerIP(ListBox lbx,TextBox tbxip,TextBox tbxnet,TextBox tbxisnet,TextBox tbxServer) { List data = new List(); var ssss = lbx.SelectedItem.ToString().Split(':'); ; try { string str = ssss[0]; int i = Convert.ToInt32(ssss[1].Trim(), 10); iep = new IPEndPoint(IPAddress.Parse(ssss[0].Trim()), Convert.ToInt32(ssss[1].Trim(), 10)); data.Add(0xf0); data.AddRange(new byte[] { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA });//010000000000//集中器的地址 data.Add(0xf1);//起始标识 data.AddRange(new byte[] { 0x00, 0x00 });//帧长度【后面再修改为正确的长度】 data.AddRange(new byte[] { 0x43, 0x00 });//控制字 data.AddRange(new byte[] { 0x00, 0x00 });//帧序号 data.AddRange(IPConvertBytes.ipAddrToBytes(tbxip));//集中器ip data.AddRange(IPConvertBytes.ipAddrToBytes(tbxisnet));//集中器子网掩码 data.AddRange(IPConvertBytes.ipAddrToBytes(tbxnet));//集中器网关 data.AddRange(IPConvertBytes.ipAddrToBytes(tbxServer));//服务器IP byte[] length = BitConverter.GetBytes(data.Count - 10 + 3);//长度【从控制字到结束标志】 data[8] = length[0]; data[9] = length[1]; byte[] temp = new byte[data.Count]; data.CopyTo(temp);//将整个 List 复制到兼容的一维数组中,从目标数组的开头开始放置。 byte[] crc = Common.CRCVerify(temp, 0, temp.Length); data.AddRange(crc);//CRC校验【从0xF0到数据位】 data.Add(0xFE); byte[] result = new byte[data.Count]; data.CopyTo(result); return result; } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } } /// /// /// ///传入IP、端口 ///传入要设置的集中器的IP ///传入要设置的集中器的子网掩码 ///传入要设置的集中器的网关 ///传入要连接的服务器的IP ///DNS public static byte[] ServerIP(ListBox lbx, TextBox tbxip, TextBox tbxnet, TextBox tbxisnet, TextBox tbxServer, TextBox txtdns) { List data = new List(); var ssss = lbx.SelectedItem.ToString().Split(':'); ; try { string str = ssss[0]; int i = Convert.ToInt32(ssss[1].Trim(), 10); iep = new IPEndPoint(IPAddress.Parse(ssss[0].Trim()), Convert.ToInt32(ssss[1].Trim(), 10)); data.Add(0xf0); data.AddRange(new byte[] { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA });//010000000000//集中器的地址 data.Add(0xf1);//起始标识 data.AddRange(new byte[] { 0x00, 0x00 });//帧长度【后面再修改为正确的长度】 data.AddRange(new byte[] { 0x43, 0x00 });//控制字 data.AddRange(new byte[] { 0x00, 0x00 });//帧序号 data.AddRange(IPConvertBytes.ipAddrToBytes(tbxip));//集中器ip data.AddRange(IPConvertBytes.ipAddrToBytes(tbxisnet));//集中器子网掩码 data.AddRange(IPConvertBytes.ipAddrToBytes(tbxnet));//集中器网关 data.AddRange(IPConvertBytes.ipAddrToBytes(tbxServer));//服务器IP data.AddRange(IPConvertBytes.ipAddrToBytes(txtdns));//DNS byte[] length = BitConverter.GetBytes(data.Count - 10 + 3);//长度【从控制字到结束标志】 data[8] = length[0]; data[9] = length[1]; byte[] temp = new byte[data.Count]; data.CopyTo(temp);//将整个 List 复制到兼容的一维数组中,从目标数组的开头开始放置。 byte[] crc = Common.CRCVerify(temp, 0, temp.Length); data.AddRange(crc);//CRC校验【从0xF0到数据位】 data.Add(0xFE); byte[] result = new byte[data.Count]; data.CopyTo(result); return result; } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } } } }

 

posted @ 2018-07-16 16:45  (时光)光阴飞逝  阅读(903)  评论(0编辑  收藏  举报