|
服務(wù)端運行界面:
0.png (12.98 KB, 下載次數(shù): 111)
下載附件
2018-6-14 22:30 上傳
客戶端云心界面:
0.png (12.61 KB, 下載次數(shù): 112)
下載附件
2018-6-14 22:30 上傳
0.png (5.44 KB, 下載次數(shù): 108)
下載附件
2018-6-14 22:19 上傳
0.png (37.77 KB, 下載次數(shù): 106)
下載附件
2018-6-14 22:30 上傳
全部資料51hei下載地址:
2、TCP_IP.rar
(5.74 MB, 下載次數(shù): 358)
2018-6-14 20:49 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
源碼預(yù)覽:
- 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;//傳遞串口接收到的數(shù)據(jù)
- public int myByLenth = 0;//串口接收到的數(shù)據(jù)長度
- public string myStr;//串口接收的字符串
- public bool receiveDtatFlag = false;
- public bool myCloseForm = false;//防止窗口關(guān)閉時線程沒有關(guān)閉占用資源
- 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);//創(chuàng)建新線程
- myThread.IsBackground = true;//線程后臺運行
- myThread.Start();//啟動線程
- }
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)//退出窗口處理
- {
- if (DialogResult.Yes == MessageBox.Show("程序正在使用中,確認(rèn)退出?", "確認(rèn)退出", 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 = "連接服務(wù)器";
- myThreadStop = false;
- this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\red.png");//bin文件中
- txbServerIP.Enabled = true;
- txbServerPort.Enabled = true;
- MessageBox.Show("連接服務(wù)器失敗 " + e.Message);
- return;
- }
- //多線程處理
- //ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg);
- //myThread = new Thread(myThreaddelegate);
- Thread myThread = new Thread(ReceiveMsg);//創(chuàng)建新線程
- myThread.IsBackground = true;//線程后臺運行
- myThread.Start();//啟動線程
- }
- else
- {
- Connected = false;
- btnConnect.Text = "連接服務(wù)器";
- 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
- ///////////////////數(shù)據(jù)多線程處理部分//////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);//提取接收數(shù)據(jù)
- //數(shù)據(jù)處理
- if (myReceByte.Length > 0)
- {
- StringBuilder builder = new StringBuilder();//避免在事件處理方法中反復(fù)的創(chuàng)建,定義到外面。
- long received_count = 0;//接收計數(shù)
- received_count += myReceByte.Length;//增加接收計數(shù)
- builder.Clear();//清除字符串構(gòu)造器的內(nèi)容
- 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") + " ");//在此實例的結(jié)尾追加指定字符串的副本
- }
- }
- else
- {
- //直接按ASCII規(guī)則轉(zhuǎn)換成字符串
- builder.Append(Encoding.ASCII.GetString(myReceByte));
- }
- //追加的形式添加到文本框末端,并滾動到最后。
- myRecvStrTemp += builder.ToString();
- myStr = builder.ToString();//字符串輸出
- if (checkBox2.Checked)//接收換行顯示
- {
- myRecvStrTemp += "\n";
- }
- try
- {
- if (receiveDtatFlag == true)//保存數(shù)據(jù)
- {
- 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;//增加接收計數(shù)
- }
- }
- //cMySession = item.Value;//兩種方法都可以
- }
- }
- #endregion
- showMsg(myRecvStrTemp);
- }
- }
- public void showMsg(string msg)//接收顯示處理部分
- {
- {
- //在線程里以安全方式調(diào)用控件
- 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 = "";//設(shè)置前n行為空
- }
- rtbReceiveMsg.Focus();
- rtbReceiveMsg.Select(rtbReceiveMsg.TextLength, 0);
- }
- private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)//清除接收窗數(shù)據(jù)
- {
- rtbReceiveMsg.Text = "";
- send_count = 0;
- textBox4.Text = "";
- txbRecvCount.Text = "";
- }
- #endregion
- #region 數(shù)據(jù)發(fā)送處理
- private void btnMySendMessage_Click(object sender, EventArgs e)//發(fā)送數(shù)據(jù)
- {
- try
- {
- if (checkBox5.Checked == true)
- {
- timer1.Enabled = true;
- }
- else
- {
- timer1.Enabled = false;
- }
- //string s = "";
- if (checkBox4.Checked)//十六進制發(fā)送
- {
- 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);//將指定基的數(shù)字的字符串表示形式轉(zhuǎn)換為等效的 8 位無符號整數(shù)。
- 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);//發(fā)送字節(jié)
- //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時,將指定字節(jié)數(shù)組中的所有字節(jié)解碼為一個字符串。。
- }
- else//ASCII發(fā)送
- {
- 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("發(fā)送數(shù)據(jù)時發(fā)生錯誤!", "錯誤提示");
- }
- }
- private void timer1_Tick(object sender, EventArgs e)//定時發(fā)送
- {
- timer1.Interval = Convert.ToInt32(textBox1.Text);
- try
- {
- if (checkBox5.Checked == true)
- {
- if (checkBox4.Checked)//十六進制發(fā)送
- {
- 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);//將指定基的數(shù)字的字符串表示形式轉(zhuǎn)換為等效的 8 位無符號整數(shù)。
- 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);//發(fā)送字節(jié)
- //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時,將指定字節(jié)數(shù)組中的所有字節(jié)解碼為一個字符串。。
- }
- else//ASCII發(fā)送
- {
- 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("發(fā)送數(shù)據(jù)時發(fā)生錯誤!", "錯誤提示");
- }
- }
- private void checkBox5_CheckedChanged(object sender, EventArgs e)//自動發(fā)送區(qū)處理
- {
- if (checkBox4.CheckState == CheckState.Checked)//發(fā)送HEX顯示
- {
- }
- else//發(fā)送ASCII顯示
- {
- timer1.Enabled = false;
- }
- }
- private void checkBox4_CheckedChanged(object sender, EventArgs e)//發(fā)送HEX區(qū)處理
- {
- string s = "";
- if (checkBox4.CheckState == CheckState.Checked)//發(fā)送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//發(fā)送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 數(shù)據(jù)保存處理
- 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
- ////////////////////外部調(diào)用接口///////////////
- #region 外部調(diào)用的發(fā)送接口
- public void mySendDataHandle(string mySendDataIn)
- {
- try
- {
- if (checkBox4.Checked)//十六進制發(fā)送
- {
- 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);//將指定基的數(shù)字的字符串表示形式轉(zhuǎn)換為等效的 8 位無符號整數(shù)。
- 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);//發(fā)送字節(jié)
- //s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生類中重寫時,將指定字節(jié)數(shù)組中的所有字節(jié)解碼為一個字符串。。
- }
- else//ASCII發(fā)送
- {
- 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("發(fā)送數(shù)據(jù)時發(fā)生錯誤!", "錯誤提示");
- }
- }//*/
- #endregion
- }
- }
復(fù)制代碼
|
評分
-
查看全部評分
|