Net Frame 1
Net Frame 1
Net Frame 1
programming
Network programming
in .Net Framework
TCP and UDP sockets, unicast,
broadcast, multicast
Contents
1. What is network
programming
In this lesson we start to study a new training course
«network programming». As we can see from the course title,
all technologies we are going to study, are directly related to
development of the applications designated for the networking
interaction between several computers.
Starting from the 60-s of the XXth century was launched
the process of creating Area Networks. On the 29th of October
1969 at 21:00 there was the first public demonstration of
the interaction possibility of several computers by means of
telephone networks. The net comprised two terminals, one of
which was at California University and the second one situated
at the distance of 600 km from it — at Stanford University.
The development was coordinated by the supervision of
Defense Advanced Research Project Agency, USA (DARPA).
And error tolerance was one of the most essential peculiarity
of the newly created network, meaning that even upon the
interaction at a network part (for example due to a nuclear
attack over the territory of the country) the rest of the network
could continue functioning.
Thus, Local Area Networks have been widely used since
the 70-s of the XX century. Consequently, there arouse a
necessity to develop the software providing interaction of
software products.
Therefore, at the time a network couldn’t have easily interacted
with the other networks built on the basis of other technical
3
STEP Computer Academy
4
Lesson 1
6
Lesson 1
3. What is a network?
Let us define the terms that we will review in the present
lesson. So, the first thing we have to do it to understand what
a «network» is.
Network is a group of the interconnected computers and
devices by means of communication links.
All these devices (computers, routers, gateways, printers)
are called nodes. Nodes are interconnected by means of the
channels, and any communication links can be used in their
capacity (cable, optical cable, optical atmospheric, radio, etc.).
Network nodes can communicate with each other within these
communication links sending messages to each other.
According to the size, networks are classified into LANs,
uniting the nodes in the framework of one building or within
a group of closely situated buildings, and WANs, which unite
several LANs.
7
STEP Computer Academy
4. OSI model
In order to formalize data exchange protocols through
communication links an ISO organization adopted a standard
protocol model that was called a 7-layer OSI model (Open System
Interconnection). Main tasks of network nodes interaction
were drawn out in the framework of this model.
Each layer of OSI model has its own assignation and each
of them is connected to an above and below layer.
Here are these 7 layers:
7 Application
6 Presentation
5 Session
4 Transport
3 Network
2 Data Link
1 Physical
9
STEP Computer Academy
5. Basic terms
Usually (or commonly) an IP protocol is used at the network
layer, meaning that each network node is assigned with a
unique network IP address.
While realizing a network application the developer should
know an IP address of the node he wants to connect to and
IP address of the node that he will be connected to.
At the network layer a developer creates a special network
API object — socket (slot), which connects a particular network
address and transport type protocol.
Using a socket the developer can realize interaction with
the other socket within a network.
Next layer is a transport layer. And we will have to stop in
more details on the topic, because exactly at a transport layer
we face applications for the first time. At the transport layer
we also face a notion of a port or end point, which describes
an application that is ready to accept a network connection
or connect with an application situated on the other node. At
the transport layer the developer should choose which of the
protocols he is going to use. There are several popular protocols
of the transport layer. The most popular protocols among the
developers are TCP (Transmission Control Protocol) and UDP
(User Datagram Protocol), RTP protocol (Real-time Transport
Protocol) is not so often used, and others.
TCP protocol is used when we need a guarantee of packages
delivery to a remote node. Working through the TCP protocol
a client establishes a connection with a server at the beginning
of a session, and by the end thereof he breaks up the connection.
10
Lesson 1
12
Lesson 1
13
STEP Computer Academy
14
Lesson 1
15
STEP Computer Academy
16
Lesson 1
6. Class Socket
Classes for working with the network are situated within
name spaces System.Net and System.Net.Sockets;
System.Net.Sockets.Socket
Thus, Socket class is a class that realizes socket interface
Berkeley on a Microsoft.Net Framework platform. As it is
shown in MSDN, Socket has a set of methods and features
for realization of network interaction. Socket class allows
transmitting and accepting data using any of communication
protocols that are within s ProtocolType list, such as:
17
STEP Computer Academy
MessageBox.Show(ex.Message);
}
19
STEP Computer Academy
finally{
s.Shutdown(SocketShutdown.Both);
s.Close();
}
20
Lesson 1
21
STEP Computer Academy
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint ep = new IPEndPoint(ip, 1024);
s.Bind(ep);
s.Listen(10);
try
{
while (true)
{
Socket ns = s.Accept();
Console.WriteLine(ns.RemoteEndPoint.ToString());
ns.Send(System.Text.Encoding.ASCII.GetBytes(DateTime.Now.ToString()));
ns.Shutdown(SocketShutdown.Both);
ns.Close();
}
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
22
Lesson 1
23
STEP Computer Academy
7. Asynchronous sockets
This simple method of interaction between a client and a
server, as it is shown in the previous example has the right for
existence, though it has a list of disadvantages, for example
if a client has to maintain connection with a server for quite
a long time, then no one will be able to connect the server
before the client releases the socket.
Though, there is an obvious solution of a problem, it is
necessary to use multi-threading, i.e. interaction with each
client has to be exercised in a separate execution flow of, that
is, to use asynchronous processing. Of course, it is possible
to implement manual multithread processing, as it is shown
in the example below:
class Server
{
delegate void ConnectDelegate (Socket s);
delegate void StartNetwork(Socket s);
Socket socket;
IPEndPoint endP;
24
Lesson 1
while (s!=null)
{
Socket ns = s.Accept();
Console.WriteLine(ns.RemoteEndPoint.ToString());
ConnectDelegate cd = new ConnectDelegate(Server_Connect);
cd.BeginInvoke(ns, null, null);
}
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
}
}
public void Start()
{
if (socket != null)
return;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
socket.Bind(endP);
socket.Listen(10);
StartNetwork start = new StartNetwork(Server_Begin);
start.BeginInvoke(socket, null, null);
}
public void Stop()
{
if (socket != null)
{
try
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
socket = null;
}
catch (SocketException ex)
{
}
}
}
}
class Program
{
static void Main(string[] args)
{
Server s = new Server("127.0.0.1", 1024);
s.Start();
Console.Read();
s.Stop();
}
}
25
STEP Computer Academy
Name Description
AcceptAsync Initiates an asynchronous operation in
order to attempt an input connection.
BeginAccept Overloaded. Initiates an asynchronous
operation in order to attempt an input
connection.
BeginConnect Overloaded. Initiates an execution of a
asynchronous request in order to connect a
remote node
BeginDisconnect Initiates an execution of an asynchronous
request in order to disconnect from a
remote terminal.
BeginReceive Overloaded. Initiates an execution of an
asynchronous data accept from a connected
Socket object.
BeginReceiveFrom Initiates an execution of an asynchronous
data accept from an indicated networking
device.
26
Lesson 1
27
STEP Computer Academy
28
Lesson 1
29
STEP Computer Academy
class AsyncServer
{
IPEndPoint endP;
Socket socket;
30
Lesson 1
31
STEP Computer Academy
socket=new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.IP);
32
Lesson 1
public Form1()
{
InitializeComponent();
}
void AddText(String text)
{
textBox1.Text+=text;
}
void RecivFunction(object obj)
{
Socket rs=(Socket) obj;
33
STEP Computer Academy
}
private void button2_Click(object sender, EventArgs e)
{
if (socket != null)
{
thread.Abort();
thread = null;
socket.Shutdown(SocketShutdown.Receive);
socket.Close();
socket = null;
textBox1.Text = " ";
}
}
socket.SendTo(System.Text.Encoding.Unicode.GetBytes(textBox2.Text),
new IPEndPoint(IPAddress.Parse("10.2.21.255"), 100));
socket.Shutdown(SocketShutdown.Send);
socket.Close();
}
34
Lesson 1
state.workSocket = socket;
RcptRes = socket.BeginReceiveFrom(state.buffer,
0,
StateObject.BufferSize,
SocketFlags.None,
ref ClientEP,
new AsyncCallback(Receive_Completed), state);
}
void Receive_Completed(IAsyncResult ia)
{
try
{
StateObject so = (StateObject)ia.AsyncState;
Socket client = so.workSocket;
if (socket == null)
return;
int readed = client.EndReceiveFrom(RcptRes, ref ClientEP);
RcptRes = socket.BeginReceiveFrom(state.buffer,
0,
StateObject.BufferSize,
35
STEP Computer Academy
SocketFlags.None,
ref ClientEP,
new AsyncCallback(Receive_Completed),
state);
}
catch (SocketException ex)
{
}
}
byte[] buffer=System.Text.Encoding.Unicode.GetBytes(textBox2.Text);
SendRes = socket.BeginSendTo(buffer, 0, buffer.Count(),
SocketFlags.None,
(EndPoint)new IPEndPoint(IPAddress.Parse("10.2.21.255"), 100),
new AsyncCallback(Send_Completed),
socket);
}
void Send_Completed(IAsyncResult ia)
{
Socket socket = (Socket)ia.AsyncState;
socket.EndSend(SendRes);
socket.Shutdown(SocketShutdown.Send);
socket.Close();
}
36
Lesson 1
8. Home assignment
1. To write network clock using datagram protocol. Here
is a service of package sending to LAN installed on a server,
and the packages contain information about the current time.
Clients display the current time. You can also make a call
system optionally.
37