C#实现TCP通讯协议

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;

using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }
        Thread threadWatch = null; // 负责监听客户端连接请求的 线程;
        Socket socketWatch = null;

        Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
        Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();

        /// <summary>
        /// 啟動監控服務
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // 创建负责监听的套接字,注意其中的参数;
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // 获得文本框中的IP对象;
            IPAddress address = IPAddress.Parse(textBox1.Text.Trim());
            // 创建包含ip和端口号的网络节点对象;
            IPEndPoint endPoint = new IPEndPoint(address, int.Parse(textBox2.Text.Trim()));
            try
            {
                // 将负责监听的套接字绑定到唯一的ip和端口上;
                socketWatch.Bind(endPoint);
            }
            catch (SocketException se)
            {
                MessageBox.Show("异常:" + se.Message);
                return;
            }
            // 设置监听队列的长度;
            socketWatch.Listen(10);
            // 创建负责监听的线程;
            threadWatch = new Thread(WatchConnecting);
            threadWatch.IsBackground = true;
            threadWatch.Start();
            ShowMsg("服务器启动监听成功!");
        }

        /// <summary>
        /// 监听客户端请求的方法;
        /// </summary>
        void WatchConnecting()
        {
            while (true)  // 持续不断的监听客户端的连接请求;
            {
                // 开始监听客户端连接请求,Accept方法会阻断当前的线程;
                Socket sokConnection = socketWatch.Accept(); // 一旦监听到一个客户端的请求,就返回一个与该客户端通信的 套接字;
                // 想列表控件中添加客户端的IP信息;
                listBox1.Items.Add(sokConnection.RemoteEndPoint.ToString());
                // 将与客户端连接的 套接字 对象添加到集合中;
                dict.Add(sokConnection.RemoteEndPoint.ToString(), sokConnection);
                ShowMsg("客户端连接成功!");
                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)
            {
                // 定义一个2M的缓存区;
                byte[] arrMsgRec = new byte[1024 * 1024 * 2];
                // 将接受到的数据存入到输入  arrMsgRec中;
                int length = -1;
                try
                {
                    length = sokClient.Receive(arrMsgRec); // 接收数据,并返回数据的长度;
                }
                catch (SocketException se)
                {
                    ShowMsg("异常:" + se.Message);
                    // 从 通信套接字 集合中删除被中断连接的通信套接字;
                    dict.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从通信线程集合中删除被中断连接的通信线程对象;
                    dictThread.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从列表中移除被中断的连接IP
                    listBox1.Items.Remove(sokClient.RemoteEndPoint.ToString());
                    break;
                }
                catch (Exception e)
                {
                    ShowMsg("异常:" + e.Message);
                    // 从 通信套接字 集合中删除被中断连接的通信套接字;
                    dict.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从通信线程集合中删除被中断连接的通信线程对象;
                    dictThread.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从列表中移除被中断的连接IP
                    listBox1.Items.Remove(sokClient.RemoteEndPoint.ToString());
                    break;
                }

                ///--------------------------------------接收客戶端發送過來的信息----------------------------------------------
                    string strMsg = System.Text.Encoding.UTF8.GetString(arrMsgRec, 1, length - 1);// 将接受到的字节数据转化成字符串;
                    ShowMsg(strMsg);


                    ///------------------------------------向客戶端發送回執信息--------------------------------------
                    string WD = strMsg.Substring(42, 4);
                    string SD = strMsg.Substring(47, 4);
                    string Mdl = strMsg.Substring(21, 10);
                    string ZOOM = strMsg.Substring(32, 1);
                    string SendTime = "20" + strMsg.Substring(3, 17) + ":000";
                    if (Mdl == "0072916200") { Mdl = "冰箱-01"; }
                    else if (Mdl == "0072915200") { Mdl = "冰箱-03"; }
                    else if (Mdl == "0072914500") { Mdl = "冰箱-04"; }
                    else if (Mdl == "0072912300") { Mdl = "冰箱-02"; }
                    SqlConnection sqlcon = new SqlConnection("Data Source=10.99.106.***;Initial Catalog=PCA_REPORT;User ID=***;pwd=***");
                    string addx = "INSERT INTO PCA_REPORT..Temperature VALUES ('" + Mdl + "','" + WD + "','" + SD + "','" + SendTime + "',getdate(),'" + ZOOM + "')";
                    DataSet ds = new DataSet();
                    SqlDataAdapter adapter = new SqlDataAdapter(addx, sqlcon);
                    adapter.Fill(ds);

                    string send = "*RR," + strMsg.Substring(3, 17) + "," + strMsg.Substring(21, 10) + "#";



                    byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(send); // 将要发送的字符串转换成Utf-8字节数组;
                    byte[] arrSendMsg = new byte[arrMsg.Length + 1];
                    arrSendMsg[0] = 0; // 表示发送的是消息数据
                    Buffer.BlockCopy(arrMsg, 0, arrSendMsg, 1, arrMsg.Length);
                    for (int i = 0; i < listBox1.Items.Count; i++)
                    {
                        string strKey = listBox1.Items[i].ToString();

                            dict[strKey].Send(arrSendMsg);// 解决了 sokConnection是局部变量,不能再本函数中引用的问题;
                            //ShowMsg(send);


                    }

            }
        }



        void ShowMsg(string str)
        {
            textBox5.AppendText(str + "\r\n");
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

    }
}

  

posted @ 2020-07-20 15:19  飞雪飘鸿  阅读(823)  评论(0编辑  收藏  举报
https://damo.alibaba.com/ https://tianchi.aliyun.com/course?spm=5176.21206777.J_3941670930.5.87dc17c9BZNvLL