当前位置:编程学习 > C#/ASP.NET >>

问个关于线程的问题

现在我正在写个接收程序,以前都是一个程序监听一个端口,用线程无限循环的去监听,现在让我用一个程序监听两个,不知道这样对服务器会不会很大 --------------------编程问答-------------------- 异步的监听循环
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Data;
using System.Windows.Forms;

namespace WSGPSGateway
{
    public partial class TcpServer : Form
    {
        public TcpServer()
        {
            InitializeComponent();
        }

        #region 自定义字段

        /// <summary>
        /// 监听控件开启状态
        /// </summary>
        private bool State = true;

        /// <summary>
        /// 声明一个线程实例
        /// </summary>
        private Thread mythread;

        /// <summary>
        /// 服务器端Ip,默认为8888
        /// </summary>
        private int _port = 8888;
        private void Selport()
        {
            DAL.XmlBase xmlbase = new DAL.XmlBase("~/Web.config");
            xmlbase.Replace("//configuration/appSettings/add[@key='Port']", "8888");
        }

        /// <summary>
        /// 保存客户端所有回话的哈希表
        /// </summary>
        private Hashtable _transmit_tb = new Hashtable();

        /// <summary>
        /// 用于接受消息的线程
        /// </summary>
        private Thread _receviccethread = null;

        /// <summary>
        /// 声明数据存放表
        /// </summary>
        public DataTable _Datatable = null;

        private delegate void GPSlist(object o1, object o2, object o3);

        #endregion

        /// <summary>
        /// 启动监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnStart_Click(object sender, EventArgs e)
        {
            try
            {
                ThreadStart thsrt = new ThreadStart(Listen);
                mythread = new Thread(thsrt);
                if (State)
                {
                    mythread.Start();
                    State = false;
                    this.BtnStart.Text = "停止监听";
                    this.Messagetxt.Text = "服务已启动,正在侦听...";
                }
                else
                {
                    mythread.Interrupt();
                    mythread.Abort();
                    State = true;
                    this.BtnStart.Text = "启动监听";
                    this.Messagetxt.Text = "服务已关闭,等待开启...";
                }
            }
            catch (Exception ex)
            {
                DAL.LogHelper.Write(DateTime.Now + ex.ToString());
            }
        }

        /// <summary>
        /// 启动监听,轮询监听客户机请求并将客户端套接字存入转发表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param> 
        private void Listen()
        {
            IPAddress _ip = IPAddress.Any;
            Socket newsoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newsoc.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            IPEndPoint locaEp = new IPEndPoint(IPAddress.Any, _port);
            try
            {
                newsoc.Bind(locaEp);
                newsoc.Listen(10);
                newsoc.BeginAccept(new AsyncCallback(onCall), newsoc);
            }
            catch (Exception ex)
            {
                DAL.LogHelper.Write(DateTime.Now + ex.ToString());
            }
        }

        /// <summary>
        /// 监听回调
        /// </summary>
        /// <param name="ar"></param>
        private void onCall(IAsyncResult ar)
        {
            try
            {
                Socket serverSoc = (Socket)ar.AsyncState;
                Socket clent = serverSoc.EndAccept(ar);
                byte[] comes = System.Text.Encoding.UTF8.GetBytes("已链接");
                EndPoint enp = clent.RemoteEndPoint;
                clent.Send(comes, comes.Length, 0);
                _transmit_tb.Add(clent.RemoteEndPoint, null);
                serverSoc.BeginAccept(new AsyncCallback(onCall), serverSoc);
                while (true)
                {
                    byte[] buffer = new byte[1024];
                    int re = clent.Receive(comes);
                    string msg = Encoding.UTF8.GetString(comes, 0, re);
                    string ip = clent.RemoteEndPoint.ToString();
                    if (msg.Length == 0)
                    {
                        _transmit_tb.Remove(clent.RemoteEndPoint);
                        _receviccethread.Interrupt();
                        _receviccethread.Abort();
                        break;
                    }
                    AddRow(ip, DateTime.Now.ToString(), msg);//添加前端显示行
                    
                    _Datatable = new DataTable("receivecontent");
                    _Datatable.PrimaryKey = new DataColumn[] { _Datatable.Columns["ID"] };
                    _Datatable.Columns.Add("ip");
                    _Datatable.Columns.Add("Receivetime");
                    _Datatable.Columns.Add("content");
                    DataRow dr = _Datatable.NewRow();
                    dr["ip"] = ip;
                    dr["Receivetime"] = DateTime.Now.ToString();
                    dr["content"] = msg;
                    _Datatable.Rows.Add(dr);

                    BLL.ClientLib.AdapterFactory.Prepare(msg);//转入适配器

                }
            }
            catch (Exception ex)
            {
                DAL.LogHelper.Write(DateTime.Now + ex.ToString());
            }
        }

        /// <summary>
        /// 关闭服务且退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnExit_Click(object sender, EventArgs e)
        {
            try
            {
                if (mythread != null)
                {
                    mythread.Interrupt();
                    mythread.Abort();
                    this.Close();
                }
                if (mythread == null)
                {
                    mythread.Interrupt();
                    mythread.Abort();
                    this.Close();
                }
                else
                {
                    this.Messagetxt.Text = "系统正在运行中...";
                }
            }
            catch (Exception ex)
            {
                DAL.LogHelper.Write(DateTime.Now + ex.ToString());
            }
        }

        /// <summary>
        /// 添加新数据
        /// </summary>
        /// <param name="o1"></param>
        /// <param name="o2"></param>
        /// <param name="o3"></param>
        public void AddRow(object o1, object o2, object o3)
        {
            if (InvokeRequired)
            {
                GPSlist gps = new GPSlist(AddRow);
                this.Invoke(gps, o1, o2, o3);
                return;
            }
            this.GPSList.Rows.Add(o1, o2, o3);
        }

        /// <summary>
        /// 窗体运行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TcpServer_Load(object sender, EventArgs e)
        {
            Form.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TcpServer_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (mythread != null)
                {
                    mythread.Interrupt();
                    mythread.Abort();
                }
                else
                {
                    this.Messagetxt.Text = "系统正在运行中...";
                }
            }
            catch (Exception ex)
            {
                DAL.LogHelper.Write(DateTime.Now + ex.ToString());
            }
        }
    }
}
--------------------编程问答-------------------- 试试就知道了,应该两个还好吧 --------------------编程问答-------------------- http://dotnet.chinaitlab.com/CSharp/780025.html --------------------编程问答--------------------
补充:.NET技术 ,  ASP.NET
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,