气体仪器WinForm代码(服务器端)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace SocketServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //定义回调:解决跨线程访问问题
        private delegate void SetTextValueCallBack(string strValue);
        //定义接收客户端发送消息的回调
        private delegate void ReceiveMsgCallBack(string strReceive);
        //声明回调
        private SetTextValueCallBack setCallBack;
        //声明
        private ReceiveMsgCallBack receiveCallBack;
        //定义回调:给ComboBox控件添加元素
        private delegate void SetCmbCallBack(string strItem);
        //声明
        private SetCmbCallBack setCmbCallBack;
        //定义发送文件的回调
        private delegate void SendFileCallBack(byte[] bf);
        //声明
        private SendFileCallBack sendCallBack;

        

        //用于通信的Socket
        Socket socketSend;
        //用于监听的SOCKET
        Socket socketWatch;
       
        //将远程连接的客户端的IP地址和Socket存入集合中
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
        //接收客户端发送消息的线程
        Thread threadReceive;
        //创建监听连接的线程
        Thread AcceptSocketThread;
        //创建用于监听SOcket是否关闭的线程
        Thread closeSocket;
        //创建用于发送数据的线程
        Thread SendMsgThread;
        Log log = new Log("D:\\IIS" + @"/log/Log.txt");
        private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (dicSocket.Count == 0)
                { }
                else
                {

                    foreach (var item in dicSocket)
                    {
                        string cjdz = "11,12";
                        string[] achara = cjdz.Split(',');

                        foreach (var item2 in achara)
                        {

                            if (dicSocket[item.Key].Poll(10, SelectMode.SelectRead))
                            {
                                string strReceiveMsg = "断开:" + dicSocket[item.Key].RemoteEndPoint;
                                string a = dicSocket[item.Key].RemoteEndPoint.ToString();
                                dicSocket[item.Key].Close();
                                txt_Log.Invoke(receiveCallBack, strReceiveMsg);
                                cmb_Socket.Items.Remove(a);
                                log.log("监听出错:" + strReceiveMsg + ",时间" + DateTime.Now);
                                dicSocket.Remove(a);


                                break;
                            }
                            else
                            {
                                string seceond = Convert.ToInt16(item2).ToString("x2") + FourOrderGas;

                                string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
                                byte[] sixmsg = HexStrTobyte(Last);
                                dicSocket[item.Key].Send(sixmsg);
                                string strReceiveMsg = "发送:" + dicSocket[item.Key].RemoteEndPoint + "发送的消息:" + Last + "时间" + DateTime.Now;
                                log.log("监听出错:" + strReceiveMsg + ",时间" + DateTime.Now);
                                this.textBox4.AppendText(strReceiveMsg + " \r \n");


                            }




                        }


                    }
                }
            }
            catch (Exception ex)
            {
                this.textBox5.AppendText("给客户端接收消息线程出错:" + ex.Message + " \r \n");
           
            }


        }
        private void btn_Start_Click(object sender, EventArgs e)
        {
            //当点击开始监听的时候 在服务器端创建一个负责监听IP地址和端口号的Socket
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //获取ip地址
            IPAddress ip = IPAddress.Parse(this.txt_IP.Text.Trim());
            //创建端口号
            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txt_Port.Text.Trim()));
            //绑定IP地址和端口号
            socketWatch.Bind(point);
            this.txt_Log.AppendText("监听成功" + " \r \n");
            btn_Start.Enabled = false;
            btn_StopListen.Enabled = true;
            //开始监听:设置最大可以同时连接多少个请求
            socketWatch.Listen(10);

            //实例化回调
            setCallBack = new SetTextValueCallBack(SetTextValue);
            receiveCallBack = new ReceiveMsgCallBack(ReceiveMsg);
            setCmbCallBack = new SetCmbCallBack(AddCmbItem);
            sendCallBack = new SendFileCallBack(SendFile);

            //创建线程
            AcceptSocketThread = new Thread(new ParameterizedThreadStart(StartListen));
            AcceptSocketThread.IsBackground = true;
            Control.CheckForIllegalCrossThreadCalls = false;
            AcceptSocketThread.Start(socketWatch);
            #region  访问网站
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
            timer.Interval = 10000;//每5秒执行一次
            timer.Enabled = true;
            #endregion
        }
        /// <summary>
        /// 等待客户端的连接,并且创建与之通信用的Socket
        /// </summary>
        /// <param name="obj"></param&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值