Network Programming :-
Network Programming is to write a program that communicates with other
programs across a computer network.
Before we go to write a server/client program first we will
understand the concept of Server, Client, IPAddress, Port, Protocol and Socket.
Server
·
A server is an entity which is a provider of
information.
Client
·
The client makes a service request from the server, which fulfills the request.
·
A client is an entity which is a seeker of
information.
IP address
An IP address
is assigned to each device on a network for the purpose of identification.
For example:
For example:
In Fig 1.1 There
are four computers in a network. If device ‘A’ wants to communicate with device
‘B’ it will connect with the IP address “192.168.2.1” because this IP address
is the address of ‘B’ computer
Port
The Port
value identifies a particular application on a device.
(The IP
address will Identify a particular device on a network but that device could
also be running multiple applications, So with the help of IP address the data
will arrive at the specific device, but if no port number is assigned the data
will be lost because the computer doesn’t know to which application data has to
be moved)
For Example:
In Fig 2.2,
On device ‘B’ there are two applications running ‘Alpha’ with port number 5000
and ‘Beta’
with port number 8000. Now if application ‘Beep’ on device ‘A’ wants to
send data to device ‘B’ to application ‘Alpha’. It will send the data to IP address
“192.168.2.1” with 5000 port number assigned. If port number is not assigned
the data cannot reach to application ‘Alpha’
Similarly if
we want to send data to device ‘B’ to application ‘Beta’ we have to define the
IP address “192.168.2.1” and port number 8000.
Socket
A socket
is one endpoint of a two way communication between two Programs running on a
network
(It is a software
component not hardware)
When the socket
is created (we will learn how to create a socket soon). It should be bound to port number and IP address once
it is bound it can be used to send and receive data.
Below explanation of sockets and protocols is not necessary at this point you can skip this part if you want to
There are
three types of socket
(1) Stream Socket.
(2) Data gram
Socket.
(3) Raw Socket.
Stream Socket
is based on TCP/IP protocol. (See
below for protocols)
Data gram
Socket is based on UDP protocol.
Note: We will use a Stream socket in our Server/Client Program which is based on TCP/IP protocol which guarantee the delivery of data
Note: We will use a Stream socket in our Server/Client Program which is based on TCP/IP protocol which guarantee the delivery of data
Protocols
(1) TCP/IP
protocol.
(2) UDP protocol.
TCP/IP protocol ensures the delivery of
message between two computers.
For example
if computer A sends some message to computer B. The TCP/IP protocol would
ensure that this message will reach at its destination computer B. TCP/IP protocol would not let the message get
lost on its way to computer B.
Real life example would be ‘E-mail’.
When you send e mail to your friend it does reach to your friend’s inbox 100%.
UDP protocol does not guarantee the
delivery of message between two computers.
For example
if computer A sends some message to computer B. The UDP protocol cannot ensure
that this message will reach at its destination B.
Real life example would be ‘Media
Streaming’ where some message (packet) might get lost. That is why when you see
any live TV show on media streaming you can get some scenes skipped.
Socket Programming
So this is
how our Server/Client program is going to work
The above diagram is like a flow chart of our socket program that we are going to make.
Creating Server…
In Fig 3.3 see
the list of functions at server side only
(1)
socket()
(2)
bind()
(3)
listen ()
(4)
accept()
(5)
recv()
(6)
send()
(7)
close()
It means
that we have to code our server program in the same sequence of steps as
mention above
So when you
are making a server program you simply have to remember these seven steps.
First step
First step is to create a socket.
Second step
In second step we use the bind()
function to “bind” this socket with IP
address and port number (details of IP address and port number are listed
above).
Third step
In third
step we use the listen() function to “Listen”
for any incoming connection from client
Listening simply means that server is ready
and looking for client .
Fourth step
In Fourth
step the server will wait until the connection request arrives from client,
when the request arrives the server will accept the client connection request
via accept()
function.
To understand what ‘connection request’ means consider the real life
example
If you want to use the facebook, you first
have to connect the facebook by sending the connection request first, you send
the connect ion request to facebook by writing
“www.facebook.com” in the URL. In this case you are client and facebook is ‘server’
Since we are still in the beginning of network
programming, In our client /server program our client connects to server by
assigning the IP address and port number of server.
(You will see in client program how the client
connects to server)
Fifth step
In Fifth step the server will again wait to
receive data from client via Receive() function
Sixth step
In sixth step the server will send data to
client via send() function.
Seventh step
In Seventh step the connection with the client
is closed via close() function.
That’s it,
just implement these seven steps in your code and you have your server
ready.
First add
two namespaces in your server program.
(1)
using System.Net;
(2)
using System.Net.Sockets;
Here are the codes of Server program…
// Preparing IP address and Port number
IPAddress ipAddress = IPAddress.Parse(“192.168.1.1”);
IPEndPoint
endPoint = new IPEndPoint(ipAddress,
8000);
// Creating a Socket -- First Step
Socket serverSocket = new
Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
// Binding the socket with endpoint which contains the IP address and port number
– Second
Step
serverSocket.Bind(endPoint);
// Server listens for connection from client – Third Step
serverSocket.Listen(10);
// Will accept the client connection request –
Fourth
Step
Socket clientConnected = serverSocket.Accept();
// Receive the data/message send by client – Fifth Step
byte[]
rcvdData = new byte[10];
int size = clientConnected.Receive(rcvdData);
string
convertedData = Encoding.ASCII.GetString(rcvdData,0,size);
Console.WriteLine(convertedData);
// Send the data/message to client – Sixth Step
Console.WriteLine("Enter Message...");
string
readData = Console.ReadLine();
clientConnected.Send(ASCIIEncoding.ASCII.GetBytes(readData));
// close the connection with client – Seventh Step
clientConnected.Close();
See server program follows the same
sequence we have discussed in Fig 3.3
Now some explanation of codes..
Ø IPAddress
ipAddress = IPAddress.Parse(“192.168.1.1”);
The above
code will assign the IP address. We have to put IP address of server. Assuming
our server and client runs on different
compter, We can also make server and
client on the same computer in that case change the ip to “127.0.0.1”
Ø IPEndPoint endPoint
= new IPEndPoint(ipAddress,
8000);
The endpoint object contains the IP address and
port number
Ø Socket serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
The above code will create a socket.
Now I will explain the details of the above code you can skip
this part as it is not necessary to go into the details at this point .
We have
discussed Stream and UDP socket above, In the below explanation I will show you
how to create Stream socket and UDP socket.
Creating Stream Socket…
Socket streamSocket
= new
Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
So Inorder to create a stream socket.
We have to specify AdressFamily to ‘InterNetwork’.
We have to specify SocketType to ‘Stream’.
We have to specify ProtocolType to ‘Tcp’.
Creating UDP Socket ….
Socket udpSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
So Inorder to create a udp socket.
We have to specify AddressFamily to
‘InterNetwork’.
We have to specify SocketType to ‘Dgram’.
We have to specify ProtocolType to ‘UDP’.
That’s it by changing the properties in code we can make either Stream
or Udp socket.
Remember in our Server/client program we will only use the stream socket.
Understanding of UDP socket is not necessary at this point. I am showing you to
create UDP Socket here only because so that you can have better
understanding of properties such as (AddressFamily,
SocketType, ProtocolType) used in the code to create a socket.
Ø serverSocket.Bind(endPoint);
The Bind() method will bind the IP address and
port number to socket via endpoint.
Ø serverSocket.Listen(10);
The server will starts to Listen for connection
from clients.
I will
explain in my next lecture that why we put the value’10’ in Listen function as
for now just remember that you have to put value ‘10’ in Listen function
Ø Socket clientConnected
= socket.Accept();
Accept()
will block the further execution of program untill there is any connection
request made by client.. When the client is connected the accept method will
accept its request and then the program will be able to execute the codes below
the Access method.
Ø byte[] rcvdData = new
byte[10];
int size = clientConnected.Receive(rcvdData);
string
convertedData = Encoding.ASCII.GetString(rcvdData,0,size);
Console.WriteLine(convertedData);
The
above first three lines of codes is used to receive data from client.
byte[]
rcvdData = new byte[10];
We have
to make Array of bytes in which the data/message is going to store sent by
client. You can put any size of Array you want to but if the data/message sent
by client is larger than the size of array you have defined then you will not
receive wole message sent by client
int
size = clientConnected.Receive(rcvdData);
Receive
method will put client message in byte Array ‘rcvdData’. Receive method also blocks the program like Accept() we have
discussed above, the Receive method blocks the program utill it did not receive
any data/message from client. Once it receive the data from client the further
execution of program can take place
string
convertedData = Encoding.ASCII.GetString(rcvdData,0,size);
Since the
data we received is in bytes from so we need to convert the data into string ‘Encoding.ASCII.GetString(rcvdData,0,size)’ will convert the bytes into string
Console.WriteLine(convertedData);
Console.WriteLine is simply printing the
convertedData on screen which contains the client message.
Ø Console.WriteLine("Enter
Message...");
string
readData = Console.ReadLine();
connectedClient.Send(ASCIIEncoding.ASCII.GetBytes(readData));
The
sbove second and third line of code will send the data/message to client
Console.WriteLine("Enter
Message...");
This
will simpliy print the “Enter Message” on screen
string readData = Console.ReadLine();
Console.ReadLine() also blocks the program like Accept() we have
discussed above, it will wait untill we put any message in that and then that
message is going to save in ‘readData’
connectedClient.Send(Encoding.ASCII.GetBytes(readData));
Inorder
to send the data to client we have to convert our string data into Bytes
“Encoding.ASCII.GetBytes(readData)” will do the job for us it will convert the
readData into Bytes
Then
the Send method will simply send the data to client.
That is all for the server program
Now heading towards the
client …
Creating Client…
In Fig 3.3
see the list of functions at client side only
(1)
socket()
(2)
connect()
(3)
send()
(4)
recv()
(5)
close()
It means
that we have to code our client program in the same sequence of steps as
mention above.
So when you are making a client program you simply have to remember these five steps.
First step
First step is
to create a socket . (Similarly
as we have created socket in server)
Second step
Second
step is to Connect that socket
via connect() function. Through the connect() function you actually made
connection request to server.
Third step
In third
step the client will send data to server
via send() function.
Fourth step
In fourth
step the client will wait to receive data from server via Receive() function.
Fifth step
In Fifth
step the connection with the server is closed via close() function.
That’s it
just implement these five steps in your code and you have your client ready.
First add
two namespaces in your client program.
(3)
using System.Net;
(4)
using System.Net.Sockets;
Here are the codes of Client
program…
// Preparing IP address
and Port number
IPAddress
ipAddress = IPAddress.Parse(“192.168.1.1”);
IPEndPoint
endPoint = new IPEndPoint(ipAddress,
8000);
// Creating a
Socket
Socket clientSocket = new
Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// connecting it
with the server
clientSocket.Connect(endPoint);
// Send the
data/message to server
Console.WriteLine("Enter Message:");
string
readData = Console.ReadLine();
clientSocket.Send(ASCIIEncoding.ASCII.GetBytes(readData));
// Receive the
data/message sent by server
byte[]
rcvdData = new byte[1];
int size = clientSocket.Receive(rcvdData);
string rcvdMsg
= ASCIIEncoding.ASCII.GetString(rcvdData, 0,
size);
Console.WriteLine(rcvdMsg);
// close the
connection with server
clientSocket.Close();
Explanation of codes..
Ø IPAddress
ipAddress = IPAddress.Parse(“192.168.1.1”);
The above code will assign the IP address.
Although this is a client program but we have to put IP address of server
because the client will connect to server with the help of IP address of
server.
Ø IPEndPoint endPoint
= new IPEndPoint(ipAddress,
8000);
The
endpoint object contains the IP address and port numberAgain we have to assign port
number of server application because with the help of port number client data
will reah at specific application.
Ø clientSocket.Connect(endPoint);
The Connect method will connect the client to
server.
Remaining codes of client is same as of the server program.
This is our simple server/client application
I Hope it helps
Thankyou for reading