Build a TCP server in Ubuntu using. NET Core

Source: Internet
Author: User
Tags getstream

Introduction and background

TCP programming is one of the most interesting aspects of network programming. In Ubuntu, I like to use. NET Core for TCP programming and use native Ubuntu scripts to communicate with a TCP server. Before, I was. The NET Framework itself writes an article about TCP servers and clients. Right now. The NET Framework itself will be open source. I want to write some communication channels between them. Basically, I'm just testing in the new. NET environment, not in the old. NET Framework environment.

However, in this article, I have a whole bunch of extra features available for you to use. I will show you the method you will use to build your own TCP server, using the. NET core assemblies and how to communicate with them over the network. I won't build anything for the client application. Instead, I will use local scripts that allow communication over TCP and UDP protocols.

The agenda is this:

    1. Build and host a TCP server with built-in. NET Core

    2. Initiates a request and uses a TCP client native script to send text data and file data to the server.

These are some of the things I will guide you in this article, and I will clarify the purpose of everything.

We are not going to build any special applications here, but TCP is the most widely used protocol in the Transport layer (as opposed to UDP), and most of the applications and services we use often rely on this protocol. HTTP,FTP,SMTP and all other similar protocols are directly dependent on TCP and use a TCP protocol-based socket (port) for communication. As a result, you can start your server from the smallest program and build a large enterprise application on it. It can be scaled based on the application programming framework and the needs of the client (or user) connected to it.

However, I'm not going to talk about how to build these complex applications, but I'll briefly explain the TCP server and client-based communication. Why write this post? I will describe TCP consumption in a cross-platform environment. I will use. NET core to create the server. The rest will be done locally, and I'll use the "NC" command in Ubuntu to communicate with the server I just created. So the idea is to let you know how to build a server in. NET core to improve efficiency and control, and how to use multiple platforms and their services to communicate with the server, enabling users to communicate with the TCP server. Well, let's get started.

Build server-side

In the. NET environment, the System.Net namespace contains all the resources available for learning and programming purposes. In the server-side programming task, I will use the TcpListener object to handle incoming TCP traffic. Basically, this is a local TCP section and you'll soon get used to it. I have been using this object as well as the programs that use this object in its life cycle, for my own personal applications and some Web-based applications, client applications, devices and machines to be able to pass through routers (modems, or WLAN hotspots, etc.). In this way, I can create a central server that communicates using the TCP protocol, and clients that can communicate using TCP can also send or receive data from this server. However, I won't go deep into submitting and transmitting data over the network in multiple formats. For the sake of simplicity, I will make things simple, so I will have to work in plain text format.

A basic demonstration of how server-client communication works in a TCP environment is demonstrated in the bitmap graphic art created below:

Figure 1: Server-Client settings

, the server controls how resources are used and used. Clients can use any device that can communicate over the network using the TCP protocol. The server processes the request and grants access to the resource. Just like interacting with other programs, TCP clients can interact with TCP servers, send commands, send requests, send option selections (for example, select Services to trigger), and so on. The TCP server then processes the requests and generates a response based on the values of those requests and the data being passed. The TCP server can:

    1. The incoming request is processed through the TCP protocol.

    2. Run as a service in the background; Which other servers can also do.

    3. Sends a data resource on the line as a byte stream.

    • Although the TCP server is considered a plain text framework for sharing messages, it is not actually a message, but rather a byte sent.

    • The sequence in TCP traffic is actually the bytes sent, not the message. Therefore, the client should be able to process the incoming bytes.

    1. Provides reliable, ordered and error-checking methods and mechanisms for communicating over the network, rather than the server we are creating, but the protocol.

In. NET core, the TCP listener allows you to handle the number of bytes available by using a fixed-size static buffer. Sometimes, data may not be sent to fill the buffer, and sometimes the buffer may not be sufficient to overwrite all buffers.

The source code for running the server is as simple as the following:

    1. Instantiates an object.

    2. Set the IP address for listening and port monitoring.

    3. Wait for the customer to connect.

This step hosts the server. At this stage, the program that hosts the server should remain active and run, or the program will terminate, shutting down the server itself. Take a look at the code given below:

    1. IPAddress address = Ipaddress.parse ("127.0.0.1");

    2. Listener = new TcpListener (address,port);

    3. Listener. Start ();

    4. The code stops the server and uses

    5. Listener. Accepttcpclientasync ();

    6. Get the function that connects the client

This code completes the work we need to do on the server side. is to host it. I use the following code to actually indicate that the server is running and is now active. The server itself does not appear to be running.

    1. Console.WriteLine ($ "Server started. Listen to TCP clients at 127.0.0.1:{port} ");

After this phase, we need to stop the server from terminating itself. Instead of keeping the same functionality, and after this line of code, I created a detached feature and added code there to wait for the client. Our class has two functions,

    1. Start the server

    2. Listening to customers

This is the second function to perform most of the work in the program. Here is where we can add asynchronous patterns and multithreading to support multiple clients connecting at the same time. However, I do not intend to delve further into this section. So, the correct code to actually start the server and listen to the client as follows:

  1. Using System;

  2. Using System.Net;

  3. Using System.Text;

  4. Using System.Net.Sockets;

  5. Namespace Consoleapplication

  6. {

  7. Class Tcphelper

  8. {

  9. Privatestatic TcpListener Listener {get; set;}

  10. Privatestaticbool Accept {get; set;} = false;

  11. Publicstaticvoid startserver (int port) {

  12. IPAddress address = Ipaddress.parse ("127.0.0.1");

  13. Listener = new TcpListener (address, port);

  14. Listener. Start ();

  15. Accept = true;

  16. Console.WriteLine ($ "Server started. Listening to TCP clients at 127.0.0.1:{port} ");

  17. }

  18. Publicstaticvoid Listen ()

  19. {

  20. if (listener! = NULL && Accept)

  21. {

  22. Continue listening.

  23. while (true)

  24. {

  25. Console.WriteLine ("Waiting for client ...");

  26. var clienttask = listener. Accepttcpclientasync (); Get the Client

  27. if (Clienttask.result! = null)

  28. {

  29. Console.WriteLine ("Client connected. Waiting for data. ");

  30. var client = Clienttask.result;

  31. String message = "";

  32. while (message! = NULL &&!message. StartsWith ("Quit"))

  33. {

  34. byte[] data = Encoding.ASCII.GetBytes ("Send Next data: [Enter ' Quit ' to terminate]");

  35. Client. GetStream (). Write (data, 0, data. Length);

  36. byte[] buffer = newbyte[1024];

  37. Client. GetStream (). Read (buffer, 0, buffer. Length);

  38. message = Encoding.ASCII.GetString (buffer);

  39. Console.WriteLine (message);

  40. }

  41. Console.WriteLine ("Closing connection.");

  42. Client. GetStream (). Dispose ();

  43. }

  44. }

  45. }

  46. }

  47. }

  48. }

This code starts the server and continues to wait for the new client. Once the client connects, it requests the data to the client and publishes the data to the client to send an "exit" to the server. Basically, this is a very simple but powerful server example for educational purposes. Of course, we now also need to call these functions from the main function in order to run the project.

    1. public static void Main (string [] args)

    2. {

    3. Start the server

    4. Tcphelper.startserver (5678);

    5. Tcphelper.listen (); Start listening

    6. }

We have now completed the server-side script. When the server is set up, it listens to the client's requests and data, which are passed on to our server. We now need to run the program and start the server to listen for requests. I don't go deep. NET core execution process and build process in depth; As for that, look at one of my other posts:

    • Using the. NET core Quick Launch on Linux

To run the program, just execute the following command,

Run dotnet

Output results

2: Server Startup

As you can see, the TCP server starts on the IP and we specify the port that we pass in the function call.

The rest is left to the client

As I mentioned earlier, I will use the local TCP client instead of the. NET core TcpClient object so that the server can be used even if. NET is not installed on the system (for example, a TcpClient object using the. NET Framework). In this article, I'll use the "netcat" command script in Unix (Linux and derived) systems. Communication can be done in a simple way. You can learn more about this script from the online resources, because I don't want to delve into it. I just want to demonstrate this usage. To learn more, you can visit any of the following URLs and learn more:

    1. Nc-unix,linux command

    2. How to use Netcat to establish and test TCP and UDP connections on a VPS

    3. NC (1)-Linux manual page

You will be able to understand how to use this command to act as a client. This also allows you to create a program script that acts as a server, listening to requests on the network, but we are not interested in these factors. Instead, we just look forward to sending a request to the server and passing some data that will be displayed on the screen.

Connect and send data to the server:

The first step is to connect to the TCP server. We need two things to make the connection,

    1. IP Address

    2. Port connection

We will pass them as parameters to the

$ NC 127.0.0.1 5678

The following screen appears (our server accepts the request and returns a message)

Figure 3: Client Connection

(Check out our server's code for more information.) )

Next, we can send the data from this terminal because it needs more data. We will send a few bytes of data and then send "exit" to terminate the connection. Let's see how this works in context.

Figure 4: The client sends data to the server

We sent three messages to the server. All of these are checked, and finally in the last message, the stream is closed and the terminal starts asking for more commands (rather than asking for more data). Why? If you notice, you will see that the "quit" command has been set to the terminator of the connection. When we send this command, the connection terminates and we need to start the connection again. Now, let's look at the other side.

Figure 5: Server-side Message log

See how the behavior of each event changes. Once our client is connected, a message is logged here: "Client connection. Wait for data ". This message is displayed when the client connects. You can also record the customer's time and other details. We pass the data, after "Exit", you can see there is a "close connection" of the log, at the other end should also show, but unfortunately, I missed this point. You must already know to use a client to connect to the server and send data.

Points of interest

Finally, this article provides a brief overview of TCP programming in. NET core and how to abstract the entire concept by using other platform services to communicate with the server.

Build a TCP server in Ubuntu using. NET Core

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.