4. Working with Sockets

Download Report

Transcript 4. Working with Sockets

TASHKENT UNIVERSITY OF INFORMATION
TECHNOLOGIES
THE DEPARTMENT OF
DATA COMMUNICATION NETWORKS AND SYSTEMS
Lecture №4
Telecommunication network software design with .NET.
Using sockets for network programming
Lector: Aliyev H.U.
Introduction
• In lessons I talked generally about .NET support for
network programming. They showed you how to
important to use .NET applications, and the classes to
work with IP addresses and sockets.
• In this lecture we'll start programming with sockets.
• In particular, we'll cover:
• - What sockets are, and the different types of sockets;
• - Socket support in .NET-the System.Net.Sockets.
Socket class;
• - Creating a TCP socket server application;
• - Setting socket options.
Sockets
•
•
•
•
A socket is one end of a two-way communication link between two programs
running on a network. By connecting the two sockets together, you can pass data
between different processes (either local or remote). The socket implementation
provides the encapsulation of the network and transport level protocols.
Sockets were originally developed for UNIX at the University of California at
Berkeley. In UNIX, the input/output method for communication follows an
open/read/write/close algorithm. Before a resource can be used, it needs to be
opened, by specifying the relevant permissions and other parameters. Once the
resource is opened, it can be read from or written to. After using the resource, the
user can finally call the Close() method, signaling to the operating system that it has
finished its tasks with the resource.
When Inter-Process Communication (IPC) and Networking facilities are added to the
UNIX operating system, they adopt the familiar pattern of Input/Output. All the
resources opened for communication are identified by a descriptor in UNIX and
Windows. These descriptors (also called handles) can be a pointer to a file, memory,
or any other channel, and actually point to an internal data structure primarily used
by the operating system. A socket, being a resource, is also represented by a
descriptor. Therefore, for sockets, a descriptor's life can be divided into three
phases: open/create socket, receive and send to socket, and ultimately closing the
socket.
The IPC interface for communicating between different processes is built on top of
the I/O methods. They facilitate sockets to send and receive data. Each target is
specified by a socket address; therefore this address can be specified in the client to
connect with the target.
Socket Communication
The socket interface based networking
Socket Types
• There are two basic types of sockets are used
• - stream sockets;
• - datagram sockets.
Stream Sockets
•
•
•
A stream socket is a connection-oriented socket that consists of a stream of bytes
that can be bi-directional, meaning that the application can both transmit and
receive through the endpoint. A stream socket guarantees error correction, handles
delivery, and preserves data sequence. It can be relied upon to deliver sequenced,
unduplicated data. It is also suitable for transmitting large amounts of data because
the overhead of establishing a separate connection for sending each message can
be unacceptable for small amounts of data. Stream sockets achieve this level of
quality through the use of the Transmission Control Protocol (TCP). TCP makes sure
that your data arrives on the other side in sequence, and error free.
In these types of sockets, a path is formed before communicating messages. This
ensures that both the sides taking part in the communication are alive and
responding. If your application sends two messages to the recipient, then the
messages are guaranteed to be received in sequence. However, individual
messages can be broken up into several packets and there is no way to determine
record boundaries. Under TCP, its up to the protocol to disassemble the
transmission of data into packets of appropriate sizes, send them over and put
them back together on the other side. An application only knows that it's sending a
certain number of bytes to the TCP layer and that the other side gets those bytes.
What TCP effectively does here is to break up that data into appropriately sized
packets, receive the packets on the other side, unwrap the data and then put it
back together.
Streams are based on explicit connections: socket A requests a connection to
socket B, and socket B accepts or rejects the connection request.
Datagram Sockets
• Datagram sockets are sometimes called connection-less sockets, that
is, no explicit connection is established-a message is sent to the
specified socket that can be received appropriately from the specified
socket. Using stream sockets is indeed a more reliable method than
datagram sockets, but with some applications, the overhead incurred
by establishing an explicit connection is unacceptable. An example
application would be a day/time server, which is proving day/time
synchronization to its clients. After all, it takes some time to establish
a reliable connection with the server, which merely delays the service
and ultimately the purpose of the server application is unseen. To
reduce the overhead we would use datagram sockets.
• The use of datagram sockets requires User Datagram Protocol (UDP)
to pass the data from a client to the server. There are some limitations
on the size of the message in this protocol, and unlike stream sockets,
where a message can be reliably sent to the destination server,
datagram sockets offer no such guarantee. There are no errors
returned from the server if the data is lost in between.
• Apart from the two types that are described above, there is also a
generalized form of sockets, called raw sockets.
Raw Sockets
• The main purpose of using raw sockets is to bypass the mechanism by
which the computer handles TCP/IP. It works by providing a custom
implementation of the TCP/IP stack replacing the mechanism provided by
the TCP/IP stack on the kernel-the packet is passed directly to the
application that needs it and therefore it is much more efficient than going
through the client's main network stack.
• A raw socket, by definition, is a socket that takes packets, bypasses the
TCP and UDP layers in the TCP/IP stack and sends them directly to the
application.
• For such sockets, the packet is not passed through the TCP/IP filter,
meaning that there is no processing on the packet, and it comes out in its
raw form. This puts the responsibility of handling all the data
appropriately, and dealing with such actions as stripping off the headers
and parsing onto the receiving application-it's like making a small TCP/IP
stack in the application. However, you rarely need to program with raw
sockets. Unless you are writing system software, or a packet analyzer type
program, you don't need to get into the details. They are mainly used
when writing custom low-level protocol applications. For example, various
TCP/IP utilities such as traceroute, ping, or arp use raw sockets.
Ports in sockets
• A port is defined to solve the problem of communicating
with multiple applications simultaneously; it basically
expands the notion of an IP address. A computer running
simultaneous applications that receives a packet though
the network can identify the target process using a unique
port number that is determined when the connection is
being made.
• The socket is composed of the IP address of the machine
and the port number used by the TCP application. Because
the IP address is unique across the Internet and the port
numbers are unique on the individual machine, the socket
numbers are also unique across the entire Internet. This
enables a process to talk to another process across the
network, based entirely on the socket number.
Client-server application using sockets
• Normally, a client-server application using sockets consists of two different
applications-a client that initiates the connection with the target (the
server), and the server, which waits for the connection from the client.
• For example, on the client side, the client must know the target's address
and the port number. To make the connection request the client tries to
establish the connection with the server:
If everything goes well, provided that the server is already running before the
client tries to connect to it, the server accepts the connection.
Upon acceptance, the server application creates a new socket to deal specifically
with the connected client.
The classes in the System.Net.Sockets
namespace
• The classes in the System.Net.Sockets namespace provide sockets
support in .NET-let's begin with a quick description of each of them.
Class
MulticastOption
Description
The MulticastOption class sets IP address values for joining or leaving an IP multicast group.
NetworkStream
The NetworkStream implements the underlying stream class from which data is sent or received. It is a
high-level abstraction representing a connection to a TCP/IP communication channel.
TcpClient
The TcpClient builds upon the Socket class to provide TCP services at a higher level. TcpClient provides
several methods for sending and receiving data over a network. Lecture 5 discusses TcpClient in more
detail.
This class also builds upon the low level Socket class; its main purpose is in server applications. This class
listens for the incoming client connections and notifies the application of any connections. We'll look
into this class when we talk about TCP.
TcpListener
UdpClient
SocketException
Socket
UDP is a connectionless protocol, therefore a different type of functionality is required to implement
UDP services in.NET.The UdpClient class serves the purpose of implementing UDP services - we'll look
more .
This is the exception thrown when an error occurs in a socket. We'll look at this class later in this chapter.
Our last class in the System.Net.Sockets namespace is the Socket class itself. This class provides the basic
functionality of a socket application.
Some of the
System.Net.Sockets.Socket methods
Method
Description
Accept()
Creates a new socket to handle the incoming connection request.
Bind()
Associates a socket with the local endpoint for listening to incoming connections.
Close()
Forces the socket to close itself.
Connect()
Establishes a connection with the remote host.
GetSocketOption()
Returns the value of a SocketOption.
IOControl()
Sets low-level operating modes for the socket. This method provides low-level access to
the underlying socket instance of the Socket class.
Listen()
Places the socket in listening mode. This method is exclusive to server applications.
Receive()
Receives data from a connected socket.
Poll()
Determines the status of the socket.
Select()
Checks the status of one or more sockets.
Send()
Sends data to the connected socket.
SetSocketOption()
Sets a SocketOption.
Shutdown()
Disables send and receive on a socket.
Creating a TCP Stream Socket
Application example
TCP-based Client Socket Application
SocketServer application
•
•
•
•
•
•
•
•
using System;
using System.Net.Sockets;
using System.Net;
•
using System.Text;
•
public class SocketServer { public static void
Main(string [] args) { // establish the local end •
point for the socket
IPHostEntry ipHost = Dns.Resolve("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new
IPEndPoint(ipAddr, 11000); // create a Tcp/Ip
Socket Socket sListener = new
Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp); // bind
the socket to the local endpoint and // listen to
the incoming sockets
try
{ sListener.Bind(ipEndPoint);
sListener.Listen(10); // Start listening for
connections while (true) {
Console.WriteLine("Waiting for a connection on
port {0}",ipEndPoint); // program is suspended
while waiting for an incoming connection
Socket handler = sListener.Accept(); string data
= null; // we got the client attempting to
connect
while(true)
{ byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes); data +=
Encoding.ASCII.GetString(bytes, 0, bytesRec); if
(data.IndexOf("<TheEnd>") > -1) { break; } } //
show the data on the console
Console.WriteLine("Text Received: {0}",data);
string theReply = "Thank you for those " +
data.Length.ToString() + " characters..."; byte[]
msg = Encoding.ASCII.GetBytes(theReply);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close(); } } catch(Exception e) {
Console.WriteLine(e.ToString()); } } // end of
Main }
Creating a TCP Stream Socket
Application
•
•
The first step is to establish the local endpoint for the socket. Before opening a
socket for listening, a socket must establish a local endpoint address. The unique
address of a TCP/IP service is defined by combining the IP address of the host with
the port number of the service to create an endpoint for the service. The Dns class
provides methods that return information about the network addresses supported
by the local network device. When the local network device has more than one
network address, or if the local system supports more than one network device, the
Dns class returns information about all network addresses, and the application must
choose the proper address for the service from the array.
We create an IPEndPoint for a server by combining the first IP address returned by
Dns.Resolve() for the host computer with a port number.
•
•
•
•
// establish the local end point for the socket
IPHostEntry ipHost = Dns.Resolve("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
•
The IPEndPoint class here represents the localhost on port number 11000.
Creating a TCP Stream Socket
Application
• Next, we create a stream socket with a new
instance of the Socket class. Having established a
local endpoint for listening, we can create the
socket:
•
•
// create a TCP/IP Socket
Socket sListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
• The AddressFamily enumeration indicates the
addressing schemes that a Socket instance can
use to resolve an address. Some important
parameters are provided in the following table.
Some important parameters of
creating the socket
Address Family value
Description
InterNetwork
Address for IP Version 4.
InterNetworkV6
Address for IP Version 6.
Ipx
IPX or SPX Address.
NetBios
NetBios Address
The SocketType parameter distinguishes between a TCP and a UDP Socket. Other
possible values are provided as follows:
SocketType value
Description
Dgram
Supports datagrams. Dgram requires the Udp ProtocolType and
the InterNetwork AddressFamily.
Raw
Supports access to the underlying transport protocol.
Stream
Supports stream sockets. Stream requires the Tcp ProtocolType
and the InterNetwork AddressFFamily
Some important parameters of
creating the socket
• The third and the last parameter defines the protocol type
that is the requested protocol for the socket. Some
important values for the ProtocolType parameter are:
ProtocolType value
Description
Raw
Raw packet protocol.
Tcp
Transmission Control Protocol.
Udp
User Datagram Protocol.
IP
Internet Protocol.
Summary
• In this lecture, we looked at developing client and
server applications with the Socket class. The
important points we have discussed include:
• What a socket is, and how sockets are introduced into
the operating system.
• The two main types of sockets are stream sockets and
datagram sockets.
• There is another type of socket, used for custom lowerlevel programming, which is known as a raw socket.
• We learned that all the socket support is provided
through the System.Net.Sockets.Socket class.
• Q&A?