在做系统监听子系统时,经常需要考虑如何使用异步套接字实现服务器监听,下面给大家展示了TCP/UDP异步套接字传输的一个简单的实现例子,供大家参考:
/*
*===SocketHelper文件========
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Xml;
namespace SocketHelper
{
public class SocketHelpr
{
///
/// 来自客户端的注册请求
///
public static string INVOKEREGISTER = “INVOKEREGISTER”;
///
/// 来自客户端的会话请求
///
public static string INVOKETALK = “INVOKETALK”;
///
/// 来自服务端的会话验证
///
public static string TALKVALIDATE = “TALKVALIDATE”;
///
/// 来自服务端的更新请求
///
public static string UPDATELIST = “UPDATELIST”;
///
/// 超时工作,当超时发生时返回连接超时
///
/// 超时时间,以毫秒为单位
/// 耗时的工作
/// 当耗时工作完成时或者达到超时时作为回调调用
public static void TimeOutAction(int iTimeOut, Action act, Action actTimeOut)
{
int iCount = 0;
bool bStart = false;
bool bExcute = false;
Thread thread = new Thread((o) =>
{
bStart = true;
try
{
act();
if (bExcute == false)
{
bExcute = true;
actTimeOut("");
}
bStart = false;
}
catch (Exception e)
{
if (bExcute == false)
{
bExcute = true;
actTimeOut(e.Message);
}
bStart = false;
}
});
Thread timer = new Thread((o) =>
{
while (true)
{
Thread.Sleep(100);
iCount++;
if (iCount * 100 >= iTimeOut)
{
if (bStart == true)
{
thread.Abort();
if (bExcute == false)
{
bExcute = true;
actTimeOut("连接超时");
}
return;
}
}
}
});
timer.IsBackground = true;
thread.IsBackground = true;
timer.Start();
thread.Start();
}
/// <summary>
/// 将byte数组转会为实体对象,该实体不支持数组或嵌套对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="buffer"></param>
/// <returns></returns>
public static T GetData<T>(byte[] buffer)
{
return XmlSerialize<T>(Encoding.Default.GetString(buffer));
}
/// <summary>
/// 将实体对象转会为byte数组,该实体不支持数组或嵌套对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tmp"></param>
/// <returns></returns>
public static byte[] GetData<T>(T tmp)
{
return Encoding.Default.GetBytes(XmlSerialize<T>(tmp));
}
/// <summary>
/// 从xml字符串序列化为实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static T XmlSerialize<T>(string xml)
{
try
{
XmlDocument xd = new XmlDocument();
xd.LoadXml(xml);
T obj = Activator.CreateInstance<T>();
foreach (XmlElement e in xd.DocumentElement.ChildNodes)
{
try
{
var pi = obj.GetType().GetProperty(e.Name);
if (pi != null && pi.GetSetMethod() != null)
pi.SetValue(obj, e.InnerText, null);
}
catch { }
}
return obj;
}
catch (Exception e)
{
return default(T);
}
}
/// <summary>
/// 将简单对象序列化为xml字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string XmlSerialize<T>(T obj)
{
string XmlHead = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><root>";
foreach (PropertyInfo pi in obj.GetType().GetProperties())
{
XmlHead += string.Format("<{0}>{1}</{0}>", pi.Name, pi.GetValue(obj, null));
}
foreach (FieldInfo fi in obj.GetType().GetFields())
{
if (fi.IsPublic == false)
continue;
XmlHead += string.Format("<{0}>{1}</{0}>", fi.Name, fi.GetValue(obj));
}
XmlHead += "</root>";
return XmlHead;
}
}
}
/*
*===========TCP异步套接字======================
*/
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using SocketHelper;
namespace TcpSocket
{
///
/// Tcp服务端
///
///
public class TcpSocketServer
{
private IPEndPoint endPoint;
private int timeOut = 5000;
private byte[] buffer = new byte[4096];
private Action