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
Dim ipAddress As IPAddress = ipAddress.Parse("127.0.0.1") |
|
//Initializes the Listener
Dim tcpListener As New
TcpListener(ipAddress, 8000) |
|
// start listening
tcpListener.Start()
|
|
|
//create new client and connect to the
sesrver
Dim tcpClient As New TcpClient
tcpClient.Connect("127.0.0.1", 8000) |
//Accept the connection
Dim soc As Socket = tcpListener.AcceptSocket() |
|
//Get the data
Dim byteData(100) As Byte
Dim size As Integer = soc.Receive(byteData) |
//reads the stream
Dim stm As Stream = tcpClient.GetStream()
//sending the data
stm.Write(byteData, 0, byteData.Length()) |
/* clean up */
soc.Close()
tcpListener.Stop() |
//closing the client connection
tcpClient.Close() |