C# SuperSocket без протокола

Вопрос прост: я прочитал всю документацию SuperSocket, но я не понимаю, есть ли способ использовать ее без реализации протокола.

Мне не нужно отправлять конкретные команды, а только байты, которые могут быть один или сотни, в зависимости от многих факторов. Мне нужно обновить старый TCP-сервер, который использует простые сокеты, он был сделан мной с использованием System.Net.Sockets libs более 4 лет назад, и я хотел бы реализовать более надежное решение с использованием библиотеки заметок, как SuperSocket.

Это хорошая идея?

Заранее спасибо.

1 ответ

Решение

Вам не нужно реализовывать протокол, вы можете просто создать 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;
            }
Другие вопросы по тегам