c#多線程socket開發

來源:互聯網
上載者:User

            話說“主機已經強制性關閉一個連結”這個問題一直拖延了很久,現在解決了,貼出來希望能購有所參考 

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;using System.Configuration;using Microsoft.Win32;using System.Diagnostics;using System.Timers;namespace WSGPSGateway{    public partial class TcpServer : Form    {        public TcpServer()        {            InitializeComponent();        }        #region 自訂欄位        public static ManualResetEvent allDone = new ManualResetEvent(false);        /// <summary>        /// 監聽控制項開啟狀態        /// </summary>        private bool State = true;        /// <summary>        /// 聲明一個線程執行個體        /// </summary>        private Thread mythread;        /// <summary>        /// 伺服器端Ip        /// </summary>        private int _port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);        /// <summary>        /// 儲存用戶端所有回話的雜湊表        /// </summary>        private Hashtable _transmit_tb = new Hashtable();        /// <summary>        /// 用於接受訊息的線程        /// </summary>        private Thread _receviccethread = null;        public struct TCPParameter        {            public string Package;            public string IpAddress;        }        #endregion        #region 監聽代碼塊        //表單運行        private void TcpServer_Load(object sender, EventArgs e)        {            this.WindowState = FormWindowState.Minimized;            this.Opacity = 0; // 表單透明度              Form.CheckForIllegalCrossThreadCalls = false;            InitializeComponent();            mythread = new Thread(Listen);            mythread.Start();            System.Timers.Timer atimer = new System.Timers.Timer();            atimer.Elapsed += new System.Timers.ElapsedEventHandler(TimeEvent);            atimer.Interval = 1000;            atimer.Enabled = true;            GC.KeepAlive(atimer);         }        private object threadlock = new object();        //啟動監聽        private void BtnStart_Click(object sender, EventArgs e)        {            //多線程        }        //啟動監聽,輪詢監聽客戶機請求並將用戶端通訊端存入轉寄表        private void Listen()        {            try            {                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);//建立串連                           newsoc.Bind(locaEp);                newsoc.Listen(100);                allDone.Reset();                newsoc.BeginAccept(new AsyncCallback(onCall), newsoc);//繼續接受其他用戶端的串連                 allDone.WaitOne();            }            catch (Exception ex)            {               //            }        }        //監聽回調        private void onCall(IAsyncResult ar)        {            allDone.Set();            Socket serverSoc = (Socket)ar.AsyncState;            Socket clent = serverSoc.EndAccept(ar);            try            {                if (serverSoc != null)                {                    byte[] comes = new byte[1024];                    EndPoint enp = clent.RemoteEndPoint;                    serverSoc.BeginAccept(new AsyncCallback(onCall), serverSoc);                    while (true)                    {                        int re = clent.Receive(comes, comes.Length, 0);                        clent.Send(Encoding.ASCII.GetBytes("8"));                        TCPParameter parm = new TCPParameter();                        parm.Package = Encoding.UTF8.GetString(comes, 0, re).ToString().Trim();                        parm.IpAddress = clent.RemoteEndPoint.ToString();                        if (parm.Package.Length != 0)                        {                            Receive(parm.Package, parm.IpAddress);                        }                    }                }            }            catch (SocketException ex)            {               //            }        }        //處理解析資料        private void Receive(string msg, string ip)        {           //        }        #endregion        #region 關閉與退出        //表單關閉        private void TcpServer_FormClosing(object sender, FormClosingEventArgs e)        {            if (mythread != null)            {                mythread.Interrupt();                mythread.Abort();                GC.Collect();            }        }        #endregion    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.