using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace Server
{
class ServerSocket
{
static void Main(string[] args)
{
TcpListener l = new TcpListener(1000); // listens on port number 1000
l.Start(); // start listener
Console.WriteLine("Server has started.Waiting for clients...");
while (true)
{
TcpClient c = l.AcceptTcpClient(); // wait for client to make request
NetworkStream ns = c.GetStream (); // access steam to send data to client.
string st = DateTime.Now.ToLongDateString(); // get system date and convert it to string
byte [] buf = System.Text.Encoding.ASCII.GetBytes (st); // convert string to an array of bytes
ns.Write(buf,0, st.Length ); // write to stream
}
} // Main()
} // end of class
} // end of namespace
Now, let us proceed to create client socket application.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
namespace Client
{
class ClientSocket
{
static void Main(string[] args)
{
// connect to server running on localhost at port no. 1000
TcpClient c = new TcpClient("localhost", 1000);
NetworkStream ns = c.GetStream(); // get stream
byte[] buf = new byte[100]; // create byte array to receive data
ns.Read(buf, 0, 100); // read data from stream into byte array
string st = System.Text.Encoding.ASCII.GetString(buf); // convert byte array to string
Console.WriteLine(st);
}
}
}
Sockets are used to build distributed applications. But for large scale applications where you have to send a lot of data sockets are too cumbersome. A better option provided by .NET is .NET Remoting. In future posts I will show how to create a simple distributed application using .NET Remoting.
Keep Learning,
Srikanth. Have anything to say about this blog, please provide your opinion using Feedback Form .