[英]C# SuperSocket without protocol
問題很簡單:我已經閱讀了整個SuperSocket文檔但我不明白是否有一種方法可以在沒有實現協議的情況下使用它。
我不需要發送特定命令,只需要發送一個或幾百個字節,具體取決於許多因素。 我需要更新一個使用簡單套接字的舊TCP服務器,它是我4年多前使用System.Net.Sockets libs制作的,我想用SuperSocket作為一個更好的解決方案。
這是個好主意嗎?
先感謝您。
您不必實現協議,只需通過實現接口創建ReceiveFilter
: IReceiveFilter
。
首先創建一個自定義的RequestInfo類,如下所示:
public class MyRequestInfo : IRequestInfo
{
public string Key { get; set; }
public string Unicode { get; set; }
// You can add more properties here
}
然后創建ReceiveFilter - ReceiveFilter基本上是過濾所有傳入消息的類。 如果您不想實現協議,這就是您所需要的。
public class MyReceiveFilter: IReceiveFilter<MyRequestInfo>
{
// This Method (Filter) is called whenever there is a new request from a connection/session
//- This sample method will convert the incomming Byte Array to Unicode string
public MyRequestInfo Filter(byte[] readBuffer, int offset, int length, bool toBeCopied, out int rest)
{
rest = 0;
try
{
var dataUnicode = Encoding.Unicode.GetString(readBuffer, offset, length);
var deviceRequest = new MyRequestInfo { Unicode = dataUnicode };
return deviceRequest;
}
catch (Exception ex)
{
return null;
}
}
public void Reset()
{
throw new NotImplementedException();
}
public int LeftBufferSize { get; }
public IReceiveFilter<MyRequestInfo> NextReceiveFilter { get; }
public FilterState State { get; }
}
下一步是創建自定義AppSession
。 會話就像客戶端連接服務器為其創建會話,並在客戶端斷開連接或服務器關閉連接時被銷毀。 這適用於需要客戶端連接然后服務器必須發送ACKnowledgment以便客戶端發送下一條消息的情況。
public class MyAppSession : AppSession<MyAppSession, MyRequestInfo>
{
// Properties related to your session.
public int ClientKey { get; set; }
public string SomeProperty { get; set; }
}
最后一步是創建自定義AppServer
// Here you will be telling the AppServer to use MyAppSession as the default AppSession class and the MyRequestInfo as the defualt RequestInfo
public class MyAppServer : AppServer<MyAppSession, MyRequestInfo>
{
// Here in constructor telling to use MyReceiveFilter and MyRequestInfo
protected MyAppServer() : base(new DefaultReceiveFilterFactory<MyReceiveFilter, MyRequestInfo>())
{
NewRequestReceived += ProcessNewMessage;
}
// This method/event will fire whenever a new message is received from the client/session
// After passing through the filter
// the requestInfo will contain the Unicode string
private void ProcessNewMessage(MyAppSession session, MyRequestInfo requestinfo)
{
session.ClientKey = SessionCount;
// Here you can access the Unicode strings that where generated in the MyReceiveFilter.Filter() Method.
Console.WriteLine(requestinfo.Unicode );
// Do whatever you want
session.Send("Hello World");
session.Close();
}
}
您還可以覆蓋AppServer類的其他方法,如: OnSessionClosed
或OnNewSessionConnected
就是這樣 - 那么你只需要初始化並啟動服務器:
var myAppServer = new MyAppServer();
if (!myAppServer.Setup(2012))
{
_logger.LogMessage(MessageType.Error, string.Format("Failed to setup server"));
return;
}
if (!myAppServer.Start())
{
_logger.LogMessage(MessageType.Error, string.Format("Failed to start server"));
return;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.