Page 1 of 1

Simple Server and telnet TCP communication elucidated

#1 foofo  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 19
  • Joined: 06-May 11

Posted 15 May 2011 - 09:43 AM

This is my first, and in definitely not my last. This tutorial aims at providing you with an in-depth knowledge into the basics of computer networking! The examples will demonstrate a simple server that allows a user to use telnet to connect and pass messages between devices. In order to fully understand this tutorial it would be recommended to read up on packets.

http://computer.hows...question525.htm

The Internet protocol (IP) is an extremely important part of our every day lives, as well as our Local Area Networks (LAN), and Wide Area Networks (WAN). IP provides a robust way of transmitting data over a network, between devices. There are many more protocols, though they’re out of our scope for this lesson. The tutorial will then later on elucidate the Transmission Control Protocol (TCP), User Datagram Protocol (UDP) is out of our scope for this tutorial bit will create one if needed.

Posted Image


TCP a connection-orientated protocol creates an end-to-end connection between network devices to ensure reliable data transmission; opposed to the UDP protocol being a connectionless orientated protocol. Thus, each UDP session is a single packet being sent to a device, not 100% guaranteed to arrive at it packets destination address.
We will be socket programming, therefore we do not directly communicate with the network device, as a file descriptor communicates with that device, making our jobs simpler.
Connection orientated sockets
    • 1. Server creates a new socket
    • 2. then binds the socket IP endpoint and port number to the system
    • 3. The server will then listen on the defined IP address and port for incoming connections.
    • 1. Client creates a new socket and binds the servers IP address, and connects.
    • 2. The client sends a synchronise (SYN) packet is sent to indicate that a new connection is to be established.
    • 3. The server will then send back SYN-ACK packet that means the server acknowledges and accepts the connection.
    • 4. Finally the client will then send back a ACK packet to establish a connection. Thus, TCP protocol utilises a three-way handshake.
    • 5. Now the client and server can transfer data over to each other. They utilises the byte data type.

Data Communication Diagram

Posted Image

When sending data to other devices that consists of both a Windows platform and an Intel processer there is no need for you to understand how the system interprets the binary data, as they will interpret the same on both machines, host and client. However, as human languages differentiate between reading right-left and left-right, the same goes for computers, this is known as endianness. Endianness differentiates between little and big. Some processors store their binary data in the little endian format, therefore storing the most significant bit first and the least last. Big endian is the opposite. Thus, if one machines send data i.e. a string saying saying “Hello World” an intel machine may send data to a machine running AMD and the Intel machine would read “Hello World”, where’s the AMD machine may read it as “World Hello”. Not exactly a valid example… Endianness has a substantial impact on communication between different systems.

The solution to this is sending data across a network all as one format. This is known as network byte order. Thus, either machine once received the data can convert to the system order (NetworkToHostOrder….).
Now after all the drabs out the way time for an example. This example a basic server command-line network chat based TCP application in C Sharp.

Server

1. Create a C Sharp Console Application

First you’re required to add the all important C Sharp network libraries, they contain socket object.

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


You will then need to declare to private fields. recv represents the amount of information received, where’s data represents the data received.
private int recv;
private byte[] data  = new byte[1024];


Most important of all you will need to define the IPEndPoint, the IPAddress/interface that you’re willing to accept connection on plus the port. In this example I will use port 65525 – you choose, however some ports are reserved for application like 21, 80, 8080, 443 etc……(more info: http://en.wikipedia....P_port_numbers)
Therefore, I could connect to this server via telnet by typing telnet connect 127.0.0.1 65525
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 65525);


You then need to define the socket that your server will communicate through. This will identify the socket and protocol type, and then address family which addresses the scheme that the socket will use to resolve an address in this case AddressFamily.InterNetwork represents an IPv4.
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,      ProtocolType.Tcp);


As the TCP diagram explain early the server will then need to bind the socket to an IPEndPoint and then listen on that socket for a connection. The socket listen methods houses a parameter of an int data type, that specifies the number of pending connections.
            serverSocket.Bind(ipep);
            serverSocket.Listen(10);


You’re then required to create a new socket that will store the accepted clients socket details. In order to have more than one client you will be required to create a multi-threaded server application which is out of our scope for this lesson.
Socket client = serverSocker.Accept();


You may wish to send a welcome messages to the connected client. In order to do this you would declare a new string message.
string welcome = “Welcome to My Server”;


and then the field declared early data, is then assigned the bytes of the welcome message.
data = Encoding.ASCII.GetBytes(welcome);


You can now send the data to the client, using the client socket plus the data, and data.Length with a socket flag identity
client.Send(data, data.Length, SocketFlags.None);


The client should now receive the message, Welcome to My Server, in telnet. This simple while loop impl,ented allow this process to be repeated with the server sending back the clients data.
           while (true)
            {
                data = new byte[1024];

                recv = client.Receive(data);

                if (recv == 0) break;

                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

                client.Send(data,recv, SocketFlags.None);
            }


Once the client has disconnected it is extremely important to close the sockets connection.
client.Close();
serverSocket.Close();


Complete source
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TCPServer
{
    class Program
    {
        static void Main(string[] args)
        {
            int recv;
            byte[] data = new byte[1024];

            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            newsock.Bind(ipep);
            newsock.Listen(10);

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

            Socket client = newsock.Accept();

            IPEndPoint clienttep = (IPEndPoint)client.RemoteEndPoint;

            Console.WriteLine("Connected with {0} at port {1}", clienttep.Address, clienttep.Port);

            string welcome = "Welcome to my Server";

            data = Encoding.ASCII.GetBytes(welcome);

            client.Send(data, data.Lengt, SocketFlags.None);

            while (true)
            {
                data = new byte[1024];

                recv = client.Receive(data);

                if (recv == 0) break;

                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

                client.Send(data,recv, SocketFlags.None);
            }

            Console.WriteLine("Disconnected from {0}", clienttep.Address);

            client.Close();
            newsock.Close();
        }
    }
}




Is This A Good Question/Topic? 3
  • +

Replies To: Simple Server and telnet TCP communication elucidated

#2 Kuggi  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 80
  • Joined: 16-January 09

Posted 30 September 2011 - 05:56 AM

Great tutorial, easy to understand and everything just works :)
Was This Post Helpful? 0
  • +
  • -

#3 Ronney  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 03-October 11

Posted 03 October 2011 - 10:36 AM

Hi,

Thanks for the tutorial, I think there is a typo with the 2nd line of the code.


using System.Network.Sockets;


I believe it should be System.Net.Sockets; instead. You got it right in the complete source code, but not on Step 1 above.

Great tutorial!

Ronney

This post has been edited by Ronney: 03 October 2011 - 10:38 AM

Was This Post Helpful? 0
  • +
  • -

#4 Bursted  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 15-April 12

Posted 15 April 2012 - 02:18 PM

Hi,

Good tutorial - works well.

The is also an 'h' missing from 'client.Send(data, data.Lengt, SocketFlags.None);' in
the complete source.


Bursted...
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1