In this tutorial, network programming is explained using a simple client server example.
For connecting between the client and the server we use windows sockets.
What is a Socket ?
A socket is a communication endpoint — an object through which a Windows
Sockets application sends or receives packets of data across a network. A socket
has a type and is associated with a running process, and it may have a name.
Currently, sockets generally exchange data only with other sockets in the same
"communication domain," which uses the Internet Protocol Suite.
Two socket types are available:
- Stream sockets
Stream sockets provide a data flow without record boundaries: a
stream of bytes. Streams are guaranteed to be delivered and to be correctly
sequenced and unduplicated.
- Datagram sockets
Datagram sockets support a record-oriented data flow that is not
guaranteed to be delivered and may not be sequenced as sent or unduplicated.
"Sequenced" means that packets are delivered in the order sent.
"Unduplicated" means that you get a particular packet only once.
Both kinds of sockets are bidirectional; ie data can be communicated in
both directions simultaneously (full-duplex).
Namespaces used
System.Net-
The System.Net namespace provides a simple programming interface
for many of the protocols used on networks.
Some of the classes in this namespace:
IPAddress |
Provides an Internet Protocol (IP)
address. |
SocketAddress |
Stores serialized information from EndPoint
derived classes. |
System.Net.Sockets-
The System.Net.Sockets namespace provides a managed
implementation of the Windows Sockets (Winsock) interface for developers who
need to tightly control access to the network.
Some of the classes in this namespace:
NetworkStream |
Provides the underlying stream of data
for network access. |
Socket |
Implements the Berkeley sockets
interface. |
SocketException |
The exception that is thrown when a
socket error occurs. |
TcpClient |
Provides client connections for TCP
network services. |
TcpListener |
Listens for connections from TCP
network clients. |
Setting Up Communication Between a Server and a Client
Server |
Client |
//Store the
IP Address
IPAddress
ipAd = IPAddress.Parse("127.0.0.1"); |
|
//Initializes the Listener
TcpListener myList=new
TcpListener(ipAd,8001); |
|
// start listening
myList.Start();
|
|
|
//create new client and connect to the
sesrver
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect("127.0.0.1",8001); |
//Accept the connection
Socket s=myList.AcceptSocket(); |
|
//Get the data
byte[] b=new
byte[100];
int k=s.Receive(b); |
//reads the stream
Stream stm = tcpclnt.GetStream();
//sending the data
stm.Write(ba,0,ba.Length); |
/* clean up */
s.Close();
myList.Stop(); |
//closing the client connection
tcpclnt.Close(); |
Click on the appropriate link below to see the video and the
source.