Let's make a head for 6 Total length of bit message , And the length does not include the example of the length field itself . Like this Socket message 000006123456.

  1. add to SuperSocket.Engine, Use it directly Nuget Search for SuperSocket.Engine Can be installed , The dependency is SuperSocket and log4net.

    Note here ,SuperSocket 2.0 There will be no SuperSocket.Engine 了 , Use it directly SuperSocket that will do , But because I'm in .net framework 4.7 Used in the environment of ,SuperSocket 2.0 The minimum support .net standard 2.1 It can only support .net core already .net 5 6 了 , So it can't be used here .

  2. Create a ReceiveFilter.

public class LengthReceiveFilter: FixedHeaderReceiveFilter<StringRequestInfo>
{
public LengthReceiveFilter() : base(6)
{
} protected override int GetBodyLengthFromHeader(byte[] header, int offset, int length)
{
return int.Parse(Encoding.Default.GetString(header, offset, length));
} protected override StringRequestInfo ResolveRequestInfo(ArraySegment<byte> header, byte[] bodyBuffer, int offset, int length)
{
return new StringRequestInfo("", Encoding.UTF8.GetString(bodyBuffer, offset, length), null);
}
}

Here we need to rewrite two methods , And call the constructor of the parent class .

public LengthReceiveFilter() : base(6) there 6 The length of the representative head is 6 position .

stay protected override int GetBodyLengthFromHeader(byte[] header, int offset, int length) In the method ,header Is the intercepted 6 Bit header byte Array ,offset It's the offset ,length It's length. , The return value is the total length of the message .

Because the first six digits in our message format are the message length in digital format , So we can use int.Parse(Encoding.Default.GetString(header, offset, length)) To get the message length , If the length includes the length itself , That's where we're going -6, Here, the length of the newspaper style is returned , If the length returned is too long , Will continue to wait for subsequent packages .

protected override StringRequestInfo ResolveRequestInfo(ArraySegment<byte> header, byte[] bodyBuffer, int offset, int length) It's the real parsing method ,

Convert our message into RequestInfo. Here we use StringRequestInfo, It is to convert the message directly into a string . among header It is the data of our message header , If you still need message headers here, start from header Take in ,bodyBuffer Is the content of our message ,offset It's the offset ,length It's length. .

If we were GetBodyLengthFromHeader The length returned in the method is longer than that of the report style , Then I will never walk to ResolveRequestInfo In this method .

  1. Create a new one MyAppServer Inherit AppServer

public class MyAppServer : AppServer
{
public MyAppServer() : base(new DefaultReceiveFilterFactory<LengthReceiveFilter,StringRequestInfo>())
{ }
}

Here we use DefaultReceiveFilterFactory This built-in factory binds our Filter.

  1. Start the server

private void button1_Click(object sender, EventArgs e)
{
AppServer appServer = new MyAppServer(); appServer.NewSessionConnected += session =>
{ }; appServer.NewRequestReceived += (session, info) =>
{
MessageBox.Show(info.Body);
session.Send("hello");
session.Close();
}; if (!appServer.Setup(1234))
{
MessageBox.Show(" Server setup failed ");
return;
} if (!appServer.Start())
{
MessageBox.Show(" Server start failed ");
return;
} }

We can directly new MyAppServer To create a server .Setup The parameter of the method is the port number , We use appServer.Setup(1234) Namely the SocketServer The listening port number is set to 1234,appServer.Start() Officially open the server .

appServer.NewSessionConnected It is an event when a new client connects , At this time, we can send a welcome message to the client , Or do something else .

appServer.NewRequestReceived It is the event of receiving a new message , We can get it here RequestInfo, So as to obtain the corresponding information . And you can go straight through Send Method to return a message .

The thing to note here is if Send Use string overloading directly , Then the default encoding format will be used , If the message UTF-8 Of , Then it is suggested to use Encoding.UTF8.GetBytes Turn into byte Array , And then use Send Array overload to send content .

  1. Shut down the server

appServer.Stop();

You can turn off the server .

SuperSocket 1.6 Create a simple message length in the header Socket More articles about servers

  1. Dependency injection [5]: Create a simple version of DI frame [ The next part ]

    In order that readers can understand .NET Core DI The implementation principle of framework has a profound understanding , We used a similar design framework called Cat Of DI frame . stay < Dependency injection [4]: Create a simple version of DI frame [ Part 1 ]> ...

  2. Dependency injection [4]: Create a simple version of DI frame [ Part 1 ]

    The purpose of this series is to analyze .NET Core The implementation principle of dependency injection framework based on , So far, through three articles (< Inversion of control >.< be based on IoC Design mode of > and < Dependency injection pattern >) From a purely theoretical point of view ...

  3. .NET CORE Learning notes series (2)—— Dependency injection [4]: Create a simple version of DI frame [ Part 1 ]

    original text https://www.cnblogs.com/artech/p/net-core-di-04.html The purpose of this series is to analyze .NET Core The implementation principle of dependency injection framework based on , So far, we have three articles from ...

  4. Use Python Create a simple Web Server

    Python 2.x In the SimpleHTTPServer modular , To Python3.x in , The module is merged into http.server Module . Use this module , You can quickly create a simple Web The server . We are C:\U ...

  5. How to use Java AWT Create a simple calculator

    Abstract : Hands teach you how to use Java AWT Create a simple calculator . This article is shared from Huawei cloud community < Hands teach you how to use Java AWT Create a simple calculator >, author : Hai Yong . About AWT AWT ( Abstract window workers ...

  6. use three.js Create a simple skybox

    The skybox created in this article is created with six pictures . The author will discuss two ways to create , Are the simplest and basic methods , It does not involve the use of shaders . One is to create a box , Then use the picture as a box 6 The texture of each face is pasted to create . The other is to simply take the texture as the scene ...

  7. .NET CORE Learning notes series (2)—— Dependency injection [5]: Create a simple version of DI frame [ The next part ]

    In order that readers can understand .NET Core DI The implementation principle of framework has a profound understanding , We used a similar design framework called Cat Of DI frame . In the last part, we introduced Cat The basic programming mode of , Now let's talk about Cat Of ...

  8. Unity Create a simple spring ( Bounce ) effect

    Reference article :http://www.cnblogs.com/SkyD/archive/2008/09/05/1284778.html Mainly based on Hooke formula F=-k·x. here k Is the stubbornness coefficient , It can be understood as k The greater the value, the more elastic ...

  9. python Basics [18]—— Use django Create a simple blog site

    One . Page implementation index.html base.html post.html header.html footer.html <!-- index.html--> {% extends 'b ...

  10. TCP/TP Programming - A simple Linux Next C Written socket Server client program

    Server side : hello_server.c #include <stdio.h> #include <stdlib.h> #include <string.h> #in ...

Random recommendation

  1. Struts2 Action And Servlet API coupling

    Unit testing is a very important link in development. When programmers finish writing code , The corresponding unit tests should also be written completely , Otherwise, your code is not convincing Struts2 take Action And Servlet Of API After decoupling , This makes unit testing very ...

  2. 【 turn 】struct and typedef struct

    original text :http://www.cnblogs.com/qyaizs/articles/2039101.html Tell me about it in three parts : 1 First :// Pay attention to C and C++ Different inside stay C To define a structure type in, use type ...

  3. Nginx - Core Module Directives

    The following is the list of directives made available by the Core module. Most of these directives ...

  4. gcc link g++ Compile the generated static library and dynamic library makefile Example

    Use c++ When developing programs or libraries , Make the library available to others . However, users use c Developed programs , link g++ When compiling the generated library , Link to gcc Generated library , Somewhat different . The first is the static library , To link g++ Compile generated libmylib.a by ...

  5. Python -- OOP senior -- __slots__、@property

    __slots__ Properties can be set Allow properties to be set class Student: __slots__ = ("name", "age") >>> ...

  6. Spark Environment building ( Four )----------- Data warehouse Hive Environment building

    Hive The background 1)MapReduce It's inconvenient to program , Need to pass Java Language, etc 2) HDFS The text on is missing Schema( Table names, column names, etc. in the database ), It's convenient for developers to pass through SQL Structured data is handled in a more efficient way , Without the need for J ...

  7. LoadRunner Vuser Interface test script Post give an example

    The content is JSON Of POST The request needs to join "EncType=application/json", Form parameters don't need .(JAVA API) // POST Interface call web.custom_r ...

  8. HDU 1573 X problem ( Standard solution of Chinese remainder theorem )

    X problem Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submis ...

  9. MySQL in char、varchar and nvarchar The difference between

    One .char and varchar The difference between char It's a fixed length , and varchar The storage space will be used according to the specific length , in addition varchar Need extra 1-2 Byte storage string length .1). When the string length is less than 255 when , Amount used ...

  10. Microsoft.Net edition

    Date Framework Visual Studio C# CLR 2002.2 1.0 Visual Studio 2002 1.0 1.0 2003.4 1.1 Visual Studio 2 ...