服务端运行界面:
客户端云心界面:
全部资料51hei下载地址:
2、TCP_IP.rar
(5.74 MB, 下载次数: 358)
源码预览:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- //添加的引用
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.IO;
- using System.Threading.Tasks;
- using System.Collections;
- namespace TCP_IP
- {
- public partial class Form1 : Form
- {
- //socket
- /*public Socket newclient;//新建socket连接口
- public bool Connected;
- public Thread myThread;
- public delegate void MyInvoke(string str);
- public IPEndPoint myIe;
- public IPAddress myIp;
- public int myPort;*/
- public delegate void MyInvoke(string str);
- MyTcpServer cMyTcpServer = new MyTcpServer();
- MySession cMySession = new MySession();// { TcpSocket = cMyTcpServer.GetType() };
- //send or receive
- public byte[] myBy;//传递串口接收到的数据
- public int myByLenth = 0;//串口接收到的数据长度
- public string myStr;//串口接收的字符串
- public bool receiveDtatFlag = false;
- public bool myCloseForm = false;//防止窗口关闭时线程没有关闭占用资源
- public bool myThreadStop = true;
- public int send_count = 0;
- public int recv_count = 0;
- public Form1()
- {
- InitializeComponent();
- }
- #region 窗体处理
- private void Form1_Load(object sender, EventArgs e)//页面加载
- {
- myCloseForm = false;
- //checkBox1.Checked = true;
- checkBox2.Checked = true;
- checkBox3.Checked = true;
- //checkBox4.Checked = true;
- button1.Visible = false;
- Thread myThread = new Thread(ReceiveMsg);//创建新线程
- myThread.IsBackground = true;//线程后台运行
- myThread.Start();//启动线程
- }
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)//退出窗口处理
- {
- if (DialogResult.Yes == MessageBox.Show("程序正在使用中,确认退出?", "确认退出", MessageBoxButtons.YesNo))
- {
- myCloseForm = true;
- this.Dispose();
- System.Environment.Exit(System.Environment.ExitCode);
- this.Close();
- e.Cancel = false;
- }
- else
- {
- e.Cancel = true;
- }
- }
- private void button1_Click(object sender, EventArgs e)//隐藏该窗口
- {
- this.Hide();
- }
- #endregion
- #region 连接按钮处理
- public void myConnect()//开启连接
- {
- //byte[] data = new byte[1024];
- if (btnConnect.Text.Trim() == "启动侦听")
- {
- btnConnect.Text = "断开连接";
- this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\green.png");//bin文件中
- txbServerIP.Enabled = false;
- txbServerPort.Enabled = false;
- cMyTcpServer.OpenServer(Convert.ToInt32(txbServerPort.Text.Trim()));
- }
- else
- {
- btnConnect.Text = "启动侦听";
- this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\red.png");//bin文件中
- txbServerIP.Enabled = true;
- txbServerPort.Enabled = true;
- cMyTcpServer.CloseServer();
- }
- /*if (Connected == false)//没有连接
- {
- newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- myIp = IPAddress.Parse(txbServerIP.Text.Trim());
- myPort = Convert.ToInt32(txbServerPort.Text.Trim());
- myIe = new IPEndPoint(myIp, myPort);
- try
- {
- newclient.Connect(myIe);
- //btnConnect.Enabled = false;
- Connected = true;
- btnConnect.Text = "断开连接";
- myThreadStop = true;
- this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\green.png");//bin文件中
- txbServerIP.Enabled = false;
- txbServerPort.Enabled = false;
- }
- catch (SocketException e)
- {
- Connected = false;
- btnConnect.Text = "连接服务器";
- myThreadStop = false;
- this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\red.png");//bin文件中
- txbServerIP.Enabled = true;
- txbServerPort.Enabled = true;
- MessageBox.Show("连接服务器失败 " + e.Message);
- return;
- }
- //多线程处理
- //ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg);
- //myThread = new Thread(myThreaddelegate);
- Thread myThread = new Thread(ReceiveMsg);//创建新线程
- myThread.IsBackground = true;//线程后台运行
- myThread.Start();//启动线程
- }
- else
- {
- Connected = false;
- btnConnect.Text = "连接服务器";
- this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\red.png");//bin文件中
- if (myThread != null)
- {
- myThread.Abort();
- //Application.ExitThread();
- }
- myThreadStop = false;
- newclient.Disconnect(false);
- txbServerIP.Enabled = true;
- txbServerPort.Enabled = true;
- }*/
- }
- private void btnConnect_Click(object sender, EventArgs e)//开启连接
- {
- myConnect();
- }
- #endregion
- ///////////////////数据多线程处理部分//////20170919////////////////////////////
- #region 真正使用的接收线程处理部分
- public void ReceiveMsg()//接收处理线程部分
- {
- while (myThreadStop)
- {
- string myRecvStrTemp = "";
- #region
- lock (cMyTcpServer.dic_ClientSocket)
- {
- foreach (var item in cMyTcpServer.dic_ClientSocket)
- {
- //cMySession = item.Value;//两种方法都可以
- if (cMyTcpServer.dic_ClientSocket.TryGetValue(item.Key.ToString(), out cMySession) == true)
- {
- byte[] myReceByte = cMySession.GetBuffer(0,cMySession.m_Buffer.Count);//提取接收数据
- //数据处理
- if (myReceByte.Length > 0)
- {
- StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复的创建,定义到外面。
- long received_count = 0;//接收计数
- received_count += myReceByte.Length;//增加接收计数
- builder.Clear();//清除字符串构造器的内容
- myBy = myReceByte;
- myByLenth = myReceByte.Length;
- if (checkBox3.Checked)//接收时间显示
- {
- if (chbRecvIpPort.Checked)//接收IP和端口显示
- {
- myRecvStrTemp += DateTime.Now.ToString("yyyy-MM-dd") + " " + DateTime.Now.ToString(@"HH\:mm\:ss\:fff") + " " + cMySession.GetIp() + "\n";
- }
- else
- {
- myRecvStrTemp += DateTime.Now.ToString("yyyy-MM-dd") + " " + DateTime.Now.ToString(@"HH\:mm\:ss\:fff") + "\n";
- }
- }
- else
- {
- if (chbRecvIpPort.Checked)//接收IP和端口显示
- {
- myRecvStrTemp += cMySession.GetIp() + "\n";
- }
- }
- //判断是否是显示为16禁止
- if (checkBox1.Checked)
- {
- //依次的拼接出16进制字符串
- foreach (byte b in myReceByte)
- {
- builder.Append(b.ToString("X2") + " ");//在此实例的结尾追加指定字符串的副本
- }
- }
- else
- {
- //直接按ASCII规则转换成字符串
- builder.Append(Encoding.ASCII.GetString(myReceByte));
- }
- //追加的形式添加到文本框末端,并滚动到最后。
- myRecvStrTemp += builder.ToString();
- myStr = builder.ToString();//字符串输出
- if (checkBox2.Checked)//接收换行显示
- {
- myRecvStrTemp += "\n";
- }
- try
- {
- if (receiveDtatFlag == true)//保存数据
- {
- string fName = saveFileDialog1.FileName;
- FileStream fs = File.Open(fName, FileMode.Append);
- StreamWriter sw = new StreamWriter(fs);
- if (checkBox3.Checked)//接收时间显示
- {
- sw.Write(DateTime.Now.ToString("yyyy-MM-dd") + " ");
- sw.Write(DateTime.Now.ToString(@"HH\:mm\:ss\:fff") + "\n");
- }
- sw.Write(builder.ToString());
- if (checkBox2.Checked)//接收换行显示
- {
- sw.WriteLine("\n");
- }
- sw.Close();
- fs.Close();
- }
- }
- catch
- {
- }
- recv_count += myReceByte.Length;//增加接收计数
- }
- }
- //cMySession = item.Value;//两种方法都可以
- }
- }
- #endregion
- showMsg(myRecvStrTemp);
- }
- }
- public void showMsg(string msg)//接收显示处理部分
- {
- {
- //在线程里以安全方式调用控件
- if ((rtbReceiveMsg.InvokeRequired) || (txbRecvCount.InvokeRequired))
- {
- MyInvoke _myinvoke = new MyInvoke(showMsg);
- rtbReceiveMsg.Invoke(_myinvoke, new object[] { msg });
- }
- else
- {
- rtbReceiveMsg.AppendText(msg);//显示部分
- txbRecvCount.Text = recv_count.ToString();
- }
- }
- }//*/
- private void rtbReceiveMsg_TextChanged(object sender, EventArgs e)//接收窗处理
- {
- if (rtbReceiveMsg.Lines.Length > 8000)//大于8000行时清楚前面的
- {
- int n = 500;
- int start = rtbReceiveMsg.GetFirstCharIndexFromLine(0);//第一行第一个字符索引
- int end = rtbReceiveMsg.GetFirstCharIndexFromLine(n);//第n行第一个字符索引
- rtbReceiveMsg.Select(start, end);//选中n行
- rtbReceiveMsg.SelectedText = "";//设置前n行为空
- }
- rtbReceiveMsg.Focus();
- rtbReceiveMsg.Select(rtbReceiveMsg.TextLength, 0);
- }
- private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)//清除接收窗数据
- {
- rtbReceiveMsg.Text = "";
- send_count = 0;
- textBox4.Text = "";
- txbRecvCount.Text = "";
- }
- #endregion
- #region 数据发送处理
- private void btnMySendMessage_Click(object sender, EventArgs e)//发送数据
- {
- try
- {
- if (checkBox5.Checked == true)
- {
- timer1.Enabled = true;
- }
- else
- {
- timer1.Enabled = false;
- }
- //string s = "";
- if (checkBox4.Checked)//十六进制发送
- {
- ArrayList al = cMyMathClass.Str16ToArrayList(rtbMySendMessage.Text);
- byte[] by = new byte[al.Count];
- int i = 0;
- foreach (string stmp in al)
- {
- by[i] += Convert.ToByte(stmp, 16);//将指定基的数字的字符串表示形式转换为等效的 8 位无符号整数。
- i++;
- }
- //int mySendLenth = newclient.Send(by);
- lock (cMyTcpServer.dic_ClientSocket)
- {
- foreach (var item in cMyTcpServer.dic_ClientSocket)
- {
- cMyTcpServer.SendData(item.Key.ToString(), by);
- }
- }
- //serialPort1.Write(by, 0, i);//发送字节
- //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生类中重写时,将指定字节数组中的所有字节解码为一个字符串。。
- }
- else//ASCII发送
- {
- int m_length = rtbMySendMessage.Text.Trim().Length;
- byte[] data = new byte[m_length];
- data = Encoding.UTF8.GetBytes(rtbMySendMessage.Text);
- lock (cMyTcpServer.dic_ClientSocket)
- {
- foreach (var item in cMyTcpServer.dic_ClientSocket)
- {
- cMyTcpServer.SendData(item.Key.ToString(), data);
- }
- }
- //int mySendLenth = newclient.Send(data);
- }
- send_count++;
- }
- catch (Exception)
- {
- MessageBox.Show("发送数据时发生错误!", "错误提示");
- }
- }
- private void timer1_Tick(object sender, EventArgs e)//定时发送
- {
- timer1.Interval = Convert.ToInt32(textBox1.Text);
- try
- {
- if (checkBox5.Checked == true)
- {
- if (checkBox4.Checked)//十六进制发送
- {
- ArrayList al = cMyMathClass.Str16ToArrayList(rtbMySendMessage.Text);
- byte[] by = new byte[al.Count];
- int i = 0;
- foreach (string stmp in al)
- {
- by[i] += Convert.ToByte(stmp, 16);//将指定基的数字的字符串表示形式转换为等效的 8 位无符号整数。
- i++;
- }
- //int mySendLenth = newclient.Send(by);
- lock (cMyTcpServer.dic_ClientSocket)
- {
- foreach (var item in cMyTcpServer.dic_ClientSocket)
- {
- cMyTcpServer.SendData(item.Key.ToString(), by);
- }
- }
- //serialPort1.Write(by, 0, i);//发送字节
- //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生类中重写时,将指定字节数组中的所有字节解码为一个字符串。。
- }
- else//ASCII发送
- {
- int m_length = rtbMySendMessage.Text.Trim().Length;
- byte[] data = new byte[m_length];
- data = Encoding.UTF8.GetBytes(rtbMySendMessage.Text);
- lock (cMyTcpServer.dic_ClientSocket)
- {
- foreach (var item in cMyTcpServer.dic_ClientSocket)
- {
- cMyTcpServer.SendData(item.Key.ToString(), data);
- }
- }
- //int mySendLenth = newclient.Send(data);
- }
- send_count++;
- }
- }
- catch (Exception)
- {
- MessageBox.Show("发送数据时发生错误!", "错误提示");
- }
- }
- private void checkBox5_CheckedChanged(object sender, EventArgs e)//自动发送区处理
- {
- if (checkBox4.CheckState == CheckState.Checked)//发送HEX显示
- {
- }
- else//发送ASCII显示
- {
- timer1.Enabled = false;
- }
- }
- private void checkBox4_CheckedChanged(object sender, EventArgs e)//发送HEX区处理
- {
- string s = "";
- if (checkBox4.CheckState == CheckState.Checked)//发送HEX显示
- {
- byte[] by = Encoding.GetEncoding("Gb2312").GetBytes(rtbMySendMessage.Text);
- rtbMySendMessage.Text = "";
- foreach (byte btmp in by)
- {
- s = "00" + string.Format("{0:X}", btmp);
- rtbMySendMessage.Text += s.Substring(s.Length - 2, 2);
- rtbMySendMessage.Text += " ";
- }
- }
- else//发送ASCII显示
- {
- ArrayList al = cMyMathClass.Str16ToArrayList(rtbMySendMessage.Text);
- byte[] by = new byte[al.Count];
- int i = 0;
- foreach (string stmp in al)
- {
- by[i] += Convert.ToByte(stmp, 16);
- i++;
- }
- rtbMySendMessage.Text = Encoding.GetEncoding("Gb2312").GetString(by);
- }
- }
- #endregion
- #region 数据保存处理
- private void checkBox6_CheckedChanged(object sender, EventArgs e)//保存勾选
- {
- if (checkBox6.CheckState == CheckState.Checked)//选中
- {
- receiveDtatFlag = true;
- }
- else
- {
- receiveDtatFlag = false;
- }
- }
- private void button4_Click(object sender, EventArgs e)//保存按钮
- {
- saveFileDialog1.Filter = "文本文件(*.txt)|*.txt";
- saveFileDialog1.FilterIndex = 1;
- saveFileDialog1.FileName = "ReceiveData";
- if (saveFileDialog1.ShowDialog() == DialogResult.OK)
- {
- string fName = saveFileDialog1.FileName;
- FileStream fs = File.Open(fName, FileMode.Append);
- StreamWriter sw = new StreamWriter(fs);
- //sw.WriteLine(richTextBox1.Text);
- textBox3.Text = fName;
- sw.Close();
- fs.Close();
- }
- }
- #endregion
- ////////////////////外部调用接口///////////////
- #region 外部调用的发送接口
- public void mySendDataHandle(string mySendDataIn)
- {
- try
- {
- if (checkBox4.Checked)//十六进制发送
- {
- ArrayList al = cMyMathClass.Str16ToArrayList(rtbMySendMessage.Text);
- byte[] by = new byte[al.Count];
- int i = 0;
- foreach (string stmp in al)
- {
- by[i] += Convert.ToByte(stmp, 16);//将指定基的数字的字符串表示形式转换为等效的 8 位无符号整数。
- i++;
- }
- //int mySendLenth = newclient.Send(by);
- lock (cMyTcpServer.dic_ClientSocket)
- {
- foreach (var item in cMyTcpServer.dic_ClientSocket)
- {
- cMyTcpServer.SendData(item.Key.ToString(), by);
- }
- }
- //serialPort1.Write(by, 0, i);//发送字节
- //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生类中重写时,将指定字节数组中的所有字节解码为一个字符串。。
- }
- else//ASCII发送
- {
- int m_length = rtbMySendMessage.Text.Trim().Length;
- byte[] data = new byte[m_length];
- data = Encoding.UTF8.GetBytes(rtbMySendMessage.Text);
- lock (cMyTcpServer.dic_ClientSocket)
- {
- foreach (var item in cMyTcpServer.dic_ClientSocket)
- {
- cMyTcpServer.SendData(item.Key.ToString(), data);
- }
- }
- //int mySendLenth = newclient.Send(data);
- }
- send_count++;
- }
- catch (Exception)
- {
- MessageBox.Show("发送数据时发生错误!", "错误提示");
- }
- }//*/
- #endregion
- }
- }
复制代码
|