NewLife.Net - Getting Started with Network Programming

Let’s not talk about the importance of network programming, let’s go to the source code first: https://github.com/nnhy/NewLife.Net.Tests

A server is to listen to some ports, receive client connections and data, process them, and then respond.

///  <summary> Define the server to manage all network sessions </summary> 
class MyNetServer : NetServer<MyNetSession>
{
}

///  <summary> Defines the session. Each remote connection uniquely corresponds to a network session, and repeats sending and receiving information again </summary> 
class MyNetSession : NetSession<MyNetServer>
{
    ///  <summary> Client connection </summary> 
    public  override  void Start()
    {
        base.Start();

        // 欢迎语
        var str = String.Format("Welcome to visit {1}!  [{0}]\r\n", Remote, Environment.MachineName);
        Send(str);
    }

    ///  <summary> Received client data </summary> 
    ///  <param name="e"></param> 
    protected  override  void OnReceive(ReceivedEventArgs e)
    {
        WriteLog( " Received: {0} " , e.Packet.ToStr());

        // Send the received data back 
        Send(e.Packet);
    }
}

The core class of the server is NetServer. Generally speaking, each network server will write its own class to inherit NetServer to facilitate writing its own NetSession session logic.

For really simple applications, you can also instantiate NetServer directly, and then process the received connection and data through events.

Here we wrote a MyNetServer without any code, just to specify which network session class to use.

Network session NetSession is very important. Each Tcp connection corresponds to a session. For Udp, the same remote socket (IP + port) is a session.

The most important parts of a network session are:

  1. The Start session starts, after the TCP three-way handshake, before the two parties have sent data packets, you can do some preparatory work at this time, or send a welcome message to the client. The Udp session starts when the first packet arrives.
  2. OnReceive receives, this method will be triggered every time a data packet is received, and the data packet is located in e.Packet. Tcp is processed synchronously by default, and will not receive the next data packet of this connection until the current data packet processing is completed.
  3. Send to send. Send Packet data packets to the client connected to this session. The extension method supports sending strings or data streams.

! ! ! Note: The sticky packet problem is dealt with before OnReceive. Next time, there will be a special article for analysis. There is also a Message in the ReceivedEventArgs of the received data, which supports the encoder to decode the data packet into a message.

 

This routine is an Echo echo program, so OnReceive sends the received data packet back as it is.

Server-side usage is simple

static NetServer _server;
static void TestServer()
{
    // Instantiate the server, specify the port, and listen on Tcp/Udp/IPv4/IPv6 
    var svr = new MyNetServer
    {
        Port = 1234,
        Log = XTrace.Log
    };
    svr.Start();

    _server = svr;
}

Specify the port and log, and you can start serving.

By default, it listens on Tcp/Udp/IPv4/IPv6, whichever protocol the client prefers to connect to.

Of course, NetServer can also support multiple ports to monitor at the same time, sharing data processing code.

 

Client usage is simpler

var uri = new NetUri("tcp://127.0.0.1:1234");
var client = uri.CreateRemote();
client.Log = XTrace.Log;
client.Received += (s, e) =>
{
    XTrace.WriteLine( " Received: {0} " , e.Packet.ToStr());
};
client.Open();

for (var i = 0; i < 5; i++)
{
    Thread.Sleep(1000);

    var str = " Hello " + (i + 1 );
    client.Send(str);
}

client. Dispose();

The NetUri here parses the protocol, address, and port directly from the string, and then CreateRemote creates the client. Tcp/Udp will be automatically recognized here.

It is also a designated log, which is convenient for us to view the working process. There are also two switches, LogSend/LogReceive, which can output more detailed packet logs.

The Received event handles the received packets.

Open starts to connect to the server, if the network is different, an exception will be thrown here. The Tcp client has a disconnection and reconnection mechanism.

Sending data packets is also very simple, just send directly. Advanced applications need to wait for response data after sending, you can use await SendAsync.

 

Because the program is very simple, you can also use the telnet command to test the server.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325499099&siteId=291194637