Only this week 80 % discount on e-learning courses of C# .NET
Get up to 60 % extra points for free! More info
discount  week 60

TCP Connection in C# .NET

In the previous lesson, Use of API in C# .NET, we showed the basics of working with an API and we created a demo application.

So above all, we'll describe how it all works and what we'll need for it.

We'll describe the Client / Server connection method. This means that we'll create a simple server that will listen on some port. To do this, we'll create a simple client that will send data to the server on the port that the server will listen to.

Everyone knows the TCP connection, but if not...

TCP (Transmission Control Protocol) is a service that is reliable unlike the UDP service. The TCP connection connects to a server or client by establishing a connection using a 3-way handshake and terminating a connection using a 4-way handshake. In real life, it might look something like this : (I hope I'm not mistaken)

Establishing a connection:

client: Hello, this is (the) client! server: Hello, this is (the) server. What you need? client: I would like to send some data, so please listen to me. :) client -> sending data...

Terminating a connection:

client: Hello, I would like to terminate the connection. server: Okay, do you really want to terminate the connection? client: Yes, I really want to. server: Okay, I am terminating the connection.

So, now back to .NET. We'll need to include two classes:

using System.Net;
using System.Net.Sockets;

So we'll create the first server:

I'll put the code here and then explain.

static byte[] data;  // 1
static Socket socket; // 1
static void Main(string[] args)
{
    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 2
    socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6666)); // 3

    socket.Listen(1); // 4
    Socket accepteddata = socket.Accept(); // 5
    data = new byte[accepteddata.SendBufferSize]; // 6
    int j = accepteddata.Receive(data); // 7
    byte[] adata = new byte[j];         // 7
    for (int i = 0; i < j; i++)         // 7
        adata[i] = data[i];             // 7
    string dat = Encoding.Default.GetString(adata); // 8
    Console.WriteLine(dat);                         // 8
}

So, now I'm going to explain what's going on in the code.

  1. I'll create a static data variable of the type byte and a socket class.
  2. I'll create a new socket with the socket type like the protocol -> note that I used ProtocolType.Tcp (unexpectedly).
  3. I'll create a new IPEndPoint, which is the destination address we want to host. In our case it's localhost. It's also possible to replace IPAddress.Par­se("127.0.0.1") with 0. And the port can be arbitrary, in our case 6666. The Bind function assigns a connection to the just mentioned IP address and port.
  4. The Listen() function is used so that the server actually knows how many users can listen to the maximum. In our case, there's only one.
  5. I don't even have to explain, I'll just create a new socket with the incoming data.
  6. The incoming data will be stored in a variable of the type byte.
  7. Simply put: "I'll re-save the incoming data to a new variable" so as not to decode still incoming data.
  8. I'll decode the data using the Default method, which I guess supports all characters -> ASCII is also a possibility and so on, and then I'll just print the incoming data to the screen.

Our server is finished. So let's get to the client which is especially simple.

using System.Net;
using System.Net.Sockets;
static void Main(string[] args)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try // 1
            {
                s.Connect(IPAddress.Parse("127.0.0.1"), 6666); // 2
                Console.Write("Enter some text : ");
                string q = Console.ReadLine();                 // 3
                byte[] data = Encoding.Default.GetBytes(q);    // 3
                s.Send(data);
            }
            catch // 1
            {
                // not connected
            }
        }

I think everything is clear, but just to be clear. (I'll no longer describe what was explained at the server.)

  1. I'll try to connect to the server. If successfully, we'll get further. If not, bad luck, for example, an error message will pop up.
  2. So I'll try to connect using the Connect function. We'll again parse the IP address from string and set the port that the server is listening on, i.e. 6666.
  3. The user enters some text, I'll save and encode it to a variable I created using the Default method. It's the data variable of the type byte.
  4. And voilà, I'll send the data to the server. :)
Console application
hosting the server
hello
Console application
Connected!
Enter some text : hello
The data sent successfully...

I tried everything, everything should go without a problem. When I'll feel like it again, we'll try making a very simple IM or maybe Snake (multiplayer). :)


 

Download

By downloading the following file, you agree to the license terms

Downloaded 6x (58.9 kB)
Application includes source codes in language C#

 

Previous article
Use of API in C# .NET
All articles in this section
Files and I/O in C# .NET
Article has been written for you by Filip Smolík
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
Activities

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!