Socket开发中之.net

本文详细介绍了TCP服务器的实现原理与监听机制,包括如何通过注册表启动服务,监听客户端请求并处理数据,实现客户端与服务器之间的通信。重点阐述了启动监听、接受连接、接收与发送数据以及关闭退出等关键步骤。
 
  • 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)
  • {
  • //此方法把启动项加载到注册表中
  • //获得应用程序路径
  • string strAssName = Application.StartupPath + @"\" + Application.ProductName + @".exe";
  • //获得应用程序名
  • string ShortFileName = Application.ProductName;
  • RegistryKey rgkRun = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
  • if(rgkRun == null)
  • {
  • rgkRun = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
  • }
  • rgkRun.SetValue(ShortFileName, strAssName);
  • 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)
  • {
  • //锁定区域同时进行数据处理
  • Monitor.Enter(threadlock);
  • try
  • {
  • //启动线程
  • ThreadStart thsrt = new ThreadStart(Listen);
  • //10个线程全部执行统一的方法
  • Thread[] threads = new Thread[10];
  • if (State) //如果状态是true,表示可以开启
  • {
  • //循环10个线程
  • for (int i = 0; i < 10; i++)
  • {
  • threads[i] = new Thread(thsrt);
  • //设置线程为后台后台线程 ,也叫守护线程
  • threads[i].IsBackground = true;
  • }
  • //循环遍历所有的10个线程
  • foreach (Thread th in threads)
  • {
  • //开启线程
  • th.Start();
  • }
  • //将状态改为false
  • State = false;
  • }
  • else
  • {
  • //中断线程
  • mythread.Interrupt();
  • //终止线程
  • mythread.Abort();
  • State = true;
  • }
  • }
  • catch (Exception ex)
  • {
  • DAL.Log.Write("线程启动时异常! \0 错误记录:" + ex.ToString() + "\r\n");
  • DAL.Log.Write("-----------------------------------------------------------\r\n");
  • }
  • finally
  • {
  • //退出对于线程的锁定
  • Monitor.Exit(threadlock);
  • }
  • }
  • //启动监听,轮询监听客户机请求并将客户端套接字存入转发表
  • 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)
  • {
  • DAL.Log.Write("启动监听时异常! \0 错误记录:" + ex.ToString() + "\r\n");
  • DAL.Log.Write("-----------------------------------------------------------\r\n");
  • }
  • }
  • //监听回调
  • 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);
  • parm.IpAddress = clent.RemoteEndPoint.ToString();
  • Receive(parm.Package, parm.IpAddress);
  • }
  • }
  • }
  • catch (SocketException ex)
  • {
  • DAL.Log.Write("---------------------------------------------------\n");
  • DAL.Log.Write("监听过程异常:" + ex.ToString()+"\r\n");
  • }
  • }
  • //处理解析数据
  • private void Receive(string msg, string ip)
  • {
  • ArrayList MessageRet = BLL.ClientLib.AdapterFactory.Prepare(msg, ip);//转入适配器并返回解析后数据
  • if (MessageRet.Count != 0)
  • {
  • BLL.ClientLib.ResloveBuffer resbuf = new BLL.ClientLib.ResloveBuffer();
  • resbuf.Prepare(MessageRet[0].ToString(), ip);//将数据二次解析后保存数据库
  • }
  • }
  • #endregion
  • #region 关闭退出
  • //窗体关闭
  • private void TcpServer_FormClosing(object sender, FormClosingEventArgs e)
  • {
  • if (mythread != null)
  • {
  • mythread.Interrupt();
  • mythread.Abort();
  • GC.Collect();
  • }
  • }
  • #endregion
  • }
  • }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值