Sunday, May 30, 2010

programs on sockets

Sockets Programming


10.1 Introduction

Most interprocess communication uses the client server model. These terms refer to

the two processes which will communicating with each other. One of the processes,

the client, connects to the other process, the server, typically to make a request for

information. A good analogy is a person who makes a phone call to another person.

The client needs to know of the existence of and the address of the server, but the

server does not need to know the address of (or even the existence of) the client

prior to the connection being established. Once a connection is established, both

sides can send and receive information.

The system calls for establishing a connection are different for the client and the

server, but both involve the basic construct of a socket. A socket is one end of an

interprocess communication channel. The two processes each establish their own

socket.

The steps for establishing a socket on the client side are:

1. Create a socket

2. Connect the socket to the address of the server

3. Send and receive data

The steps for establishing a socket on the server side are:

1. Create a socket

2. Bind the socket to an address. For the server socket on the Internet, an address

consists of a port number on the host machine.

3. Listen for connections.

4. Accept a connection. This call typically blocks until a client connects with the

server.

137

138 CHAPTER 10. SOCKETS PROGRAMMING

5. Send and receive data.

Thus a socket is a communication mechanism. A socket is normally identified by an

integer which may be called the socket descriptor. The socket mechanism was first

introduced in the 4.2 BSD Unix system in 1983 in conjunction with the TCP/IP

protocols that first appeared in the 4.1 BSD Unix system in late 1981.

Thus besides the IPAddress we also need a port number (2 bytes) which is arbitrary

except for the well know port numbers associated with popular applications.

Formally a socket is defined by a group of four numbers. There are

1) The remote host identification number or address (IPAddress)

2) The remote host port number

3) The local host identification number or address (IPAddress)

4) The local host port number

10.2 Transmission Control Protocol

TCP is reliable connection oriented protocol.

Example 1. When the server program is run it will indicate at which IPAddress

it is running and the port it is listening to. Now run the client program so that we

establish a connection with the server. When the connection is established the server

will display the IPAddress and port from where it has accepted the connection. The

client will ask for the string which is to be transmitted to the server. The server on

reciept of the string will display it, send an acknowledgement which will be received

by the client.

10.2. TRANSMISSION CONTROL PROTOCOL 139

// Server1.cs

using System;

using System.Text;

using System.Net;

using System.Net.Sockets;

class Server1

{

public static void Main()

{

try

{

// use local IP address and use the same in the client

IPAddress ipAd = IPAddress.Parse("152.106.40.84");

TcpListener listener = new TcpListener(ipAd,2055);

// start listening at the specified port 2055

listener.Start();

Console.WriteLine("Server is running at port 2055...");

Console.WriteLine("The local End point is: " + listener.LocalEndpoint);

Console.WriteLine("Waiting for a connection...");

Socket s = listener.AcceptSocket();

Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

byte[] b = new byte[100];

int k = s.Receive(b);

Console.WriteLine("Received...");

for(int i=0;i

Console.Write(Convert.ToChar(b[i]));

ASCIIEncoding asen = new ASCIIEncoding();

s.Send(asen.GetBytes("The string was received by the server."));

Console.WriteLine("\nSent Acknowledgement");

// clean up

s.Close();

listener.Stop();

} // end try

catch(Exception e)

{

Console.WriteLine("Error... " + e.StackTrace);

} // end catch

} // end Main

} // end class Server1

140 CHAPTER 10. SOCKETS PROGRAMMING

// Client1.cs

using System;

using System.IO;

using System.Text;

using System.Net;

using System.Net.Sockets;

class Client1

{

public static void Main()

{

try

{

TcpClient tcpclnt = new TcpClient();

Console.WriteLine("Connecting...");

tcpclnt.Connect("152.106.40.84",2055);

Console.WriteLine("Connected");

Console.Write("Enter the string to be transmitted: ");

String str = Console.ReadLine();

Stream stm = tcpclnt.GetStream();

ASCIIEncoding asen = new ASCIIEncoding();

byte[] ba = asen.GetBytes(str);

Console.WriteLine("Transmitting...");

stm.Write(ba,0,ba.Length);

byte[] bb = new byte[100];

int k = stm.Read(bb,0,100);

for(int i=0;i

Console.Write(Convert.ToChar(bb[i]));

// clean up

tcpclnt.Close();

} // end try

catch(Exception e)

{

Console.WriteLine("Error... " + e.StackTrace);

} // end catch

} // end Main

} // end class Client1

10.2. TRANSMISSION CONTROL PROTOCOL 141

Example 2. In our second example we include an xml-file (Server2.exe.config)

on the Server side we can query from the Client. On the Server side we first compile

csc /D:LOG Server2.cs

The code between #if LOG and endif will be added by the compiler only if the symbol

LOG is defined during compilation (conditional compilation). Next we compile

the Client side

csc Client2.cs

Then on the Server side we start running the exe-file Server2 and finally we start

the exe-file Client2 on the Client side.

// Server2.cs

using System;

using System.Threading;

using System.IO;

using System.Net;

using System.Net.Sockets;

using System.Configuration;

class EmployeeTCPServer

{

static TcpListener listener;

const int LIMIT = 5; // 5 concurrent clients

public static void Main()

{

IPAddress ipAd = IPAddress.Parse("152.106.40.84");

listener = new TcpListener(ipAd,2055);

listener.Start();

#if LOG

Console.WriteLine("Server mounted,listening to port 2055");

#endif

for(int i=0;i

{

Thread t = new Thread(new ThreadStart(Service));

t.Start();

} // end for loop

} // end Main

public static void Service()

{

while(true)

142 CHAPTER 10. SOCKETS PROGRAMMING

{

Socket soc = listener.AcceptSocket();

#if LOG

Console.WriteLine("Connected: {0}",soc.RemoteEndPoint);

#endif

try

{

Stream s = new NetworkStream(soc);

StreamReader sr = new StreamReader(s);

StreamWriter sw = new StreamWriter(s);

sw.AutoFlush = true; // enable automatic flushing

sw.WriteLine("{0} Employees available",ConfigurationManager.AppSettings.Count);

while(true)

{

string name = sr.ReadLine();

if(name == ""

name == null) break;

string job = ConfigurationManager.AppSettings[name];

if(job == null) job = "No such employee";

sw.WriteLine(job);

} // end while

s.Close();

} // end try

catch(Exception e)

{

#if LOG

Console.WriteLine(e.Message);

#endif

} // end catch

#if LOG

Console.WriteLine("Disconnected: {0}",soc.RemoteEndPoint);

#endif

soc.Close();

}

}

} // end class Server2

10.2. TRANSMISSION CONTROL PROTOCOL 143

The file (xml-file) Server2.exe.config is given by















No comments:

Post a Comment