简体   繁体   English

没有协议的C#SuperSocket

[英]C# SuperSocket without protocol

The question is simple: I've read the whole SuperSocket documentation but I don't understand if there is a way to use it without implement a protocol. 问题很简单:我已经阅读了整个SuperSocket文档但我不明白是否有一种方法可以在没有实现协议的情况下使用它。

I don't need to send specific commands but only bytes which might be one or hundreds, depending by many factors. 我不需要发送特定命令,只需要发送一个或几百个字节,具体取决于许多因素。 I need to renew an old TCP server that uses simple sockets, it was made by me using System.Net.Sockets libs more than 4 years ago and I'd like to realize a stronger solution using a well note library as SuperSocket is. 我需要更新一个使用简单套接字的旧TCP服务器,它是我4年多前使用System.Net.Sockets libs制作的,我想用SuperSocket作为一个更好的解决方案。

Is it a good idea? 这是个好主意吗?

Thank you in advance. 先感谢您。

You don't have to implement a protocol, you can simply create a ReceiveFilter by implementing the interface: IReceiveFilter . 您不必实现协议,只需通过实现接口创建ReceiveFilterIReceiveFilter

So first create a custom RequestInfo class like the one below: 首先创建一个自定义的RequestInfo类,如下所示:

public class MyRequestInfo : IRequestInfo
{
    public string Key { get; set; }
    public string Unicode { get; set; }

    // You can add more properties here
}

Then create the ReceiveFilter - the ReceiveFilter is basically the class which filters all incoming messages. 然后创建ReceiveFilter - ReceiveFilter基本上是过滤所有传入消息的类。 This is what you need if you don't want to implement a protocol. 如果您不想实现协议,这就是您所需要的。

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; }
}

Next Step is to create a custom AppSession . 下一步是创建自定义AppSession Session is like when a client connects the server creates a session for it, and is destroyed when the client disconnects or when the server closes the connection. 会话就像客户端连接服务器为其创建会话,并在客户端断开连接或服务器关闭连接时被销毁。 This is good for situations when you need the client to connect and then the server has to send ACKnowledgment for the client to send the next message. 这适用于需要客户端连接然后服务器必须发送ACKnowledgment以便客户端发送下一条消息的情况。

public class MyAppSession : AppSession<MyAppSession, MyRequestInfo>
{
    // Properties related to your session.

    public int ClientKey { get; set; }

    public string SomeProperty { get; set; }

}

And the Final Step is to create your custom AppServer 最后一步是创建自定义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();
    }
}

You can also override other methods of the AppServer class like: OnSessionClosed or OnNewSessionConnected 您还可以覆盖AppServer类的其他方法,如: OnSessionClosedOnNewSessionConnected

That's it - then you just have to initialise and start the server: 就是这样 - 那么你只需要初始化并启动服务器:

            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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM