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:
Build and host a TCP server with built-in. NET Core
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:
The incoming request is processed through the TCP protocol.
Run as a service in the background; Which other servers can also do.
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.
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:
Instantiates an object.
Set the IP address for listening and port monitoring.
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:
IPAddress address = Ipaddress.parse ("127.0.0.1");
Listener = new TcpListener (address,port);
Listener. Start ();
The code stops the server and uses
Listener. Accepttcpclientasync ();
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.
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,
Start the server
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:
Using System;
Using System.Net;
Using System.Text;
Using System.Net.Sockets;
Namespace Consoleapplication
{
Class Tcphelper
{
Privatestatic TcpListener Listener {get; set;}
Privatestaticbool Accept {get; set;} = false;
Publicstaticvoid startserver (int port) {
IPAddress address = Ipaddress.parse ("127.0.0.1");
Listener = new TcpListener (address, port);
Listener. Start ();
Accept = true;
Console.WriteLine ($ "Server started. Listening to TCP clients at 127.0.0.1:{port} ");
}
Publicstaticvoid Listen ()
{
if (listener! = NULL && Accept)
{
Continue listening.
while (true)
{
Console.WriteLine ("Waiting for client ...");
var clienttask = listener. Accepttcpclientasync (); Get the Client
if (Clienttask.result! = null)
{
Console.WriteLine ("Client connected. Waiting for data. ");
var client = Clienttask.result;
String message = "";
while (message! = NULL &&!message. StartsWith ("Quit"))
{
byte[] data = Encoding.ASCII.GetBytes ("Send Next data: [Enter ' Quit ' to terminate]");
Client. GetStream (). Write (data, 0, data. Length);
byte[] buffer = newbyte[1024];
Client. GetStream (). Read (buffer, 0, buffer. Length);
message = Encoding.ASCII.GetString (buffer);
Console.WriteLine (message);
}
Console.WriteLine ("Closing connection.");
Client. GetStream (). Dispose ();
}
}
}
}
}
}
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.
public static void Main (string [] args)
{
Start the server
Tcphelper.startserver (5678);
Tcphelper.listen (); Start listening
}
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:
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:
Nc-unix,linux command
How to use Netcat to establish and test TCP and UDP connections on a VPS
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,
IP Address
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