标签:c event-handling tcp
我目前正在研究一种简单的客户端/服务器模型,它在TCP数据包(如HTTP)中发送数据包,命令基本上是整数(每个数据包的前4个字节),我想找出一种有效的方法.处理这些命令.
最明显的答案是编写成千上万的if或者用千个案例做一个巨大的switch语句,但是没有更好的方法吗?
我想创建一个事件数组,然后只提高相应的索引,以便每个int引用一个被命名的事件(例如MessageReceived).我也想节省时间,所以我怎么能解决这个问题呢?
编辑:服务器处理多个连接,每个连接一个连接的客户端,因此在我的情况下为每个命令创建单独的连接是没有用的.
解决方法:
听起来像是一份工作!
enum YourEnum
{
DoThis,
DoThat
}
YourEnum foo = (YourEnum)yourInt;
Visual Studio甚至可以使用内置的代码片段创建整个switch语句,并且您的代码变得非常易读.
switch(foo)
变
switch(foo)
{
case YourEnum.DoThis:
break;
case YourEnum.DoThat:
break;
default:
break;
}
更新1
从可维护性的角度来看,这有点可怕,但是如果你创建了一个类:
public class ActionProcessor
{
public void Process(int yourInt)
{
var methods = this.GetType().GetMethods();
if (methods.Length > yourInt)
{
methods[yourInt].Invoke(this, null);
}
}
public DoThis()
{
}
public DoThat()
{
}
或者更好但更难维护:
[AttributeUsageAttribute(AttributeTargets.Method,
Inherited = false,
AllowMultiple = false)]
public sealed class AutoActionAttribute : Attribute
{
public AutoActionAttibute(int methodID)
{
this.MethodID = methodID;
}
public int MethodID { get; set; }
}
public class ActionProcessor
{
public void Process(int yourInt)
{
var method = this.GetType().GetMethods()
.Where(x => x.GetCustomAttribute(typeof(AutoActionAttribute),
false) != null
&& x.GetCustomAttribute(typeof(AutoActionAttribute),
false).MethodID == yourInt)
.FirstOrDefault();
if (method != null)
{
method.Invoke(this, null);
}
}
[AutoAction(1)]
public DoThis()
{
}
[AutoAction(2)]
public DoThat()
{
}
}
更新2(编码我认为Josh C.正在谈论的内容)
// Handles all incoming requests.
public class GenericProcessor
{
public delegate void ActionEventHandler(object sender, ActionEventArgs e);
public event ActionEventHandler ActionEvent;
public ProcessAction(int actionValue)
{
if (this.ActionEvent != null)
{
this.ActionEvent(this, new ActionEventArgs(actionValue));
}
}
}
// Definition of values for request
// Extend as needed
public class ActionEventArgs : EventArgs
{
public ActionEventArgs(int actionValue)
{
this.ActionValue = actionValue;
}
public virtual int ActionValue { get; private set; }
}
这样你就创建了负责某些值的SomeActionProcessor:
// Handles a specific (or multiple) requests
public class SomeActionProcessor
{
public void HandleActionEvent(object sender, ActionEventArgs e)
{
if (e.ActionValue == 1)
{
this.HandleAction();
}
}
private void HandleAction()
{
}
}
然后创建类并连接它们:
GenericProcessor gp = new GenericProcessor();
SomeActionProcessor sap = new SomeActionProcessor();
gp.ActionEvent += sap.HandleActionEvent;
火灾和发送通用处理器请求:
gp.ProcessAction(1);
标签:c,event-handling,tcp 来源: https://codeday.me/bug/20190625/1288117.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。