CLIENT CODE
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
class Client {
public static void Main(String[] args) {
TcpClient tcpc = new TcpClient();
Byte[] read = new Byte[32];
if (args.Length != 1) {
Console.WriteLine("Please specify a server name in the command
line");
return;
}
String server = args[0];
// Verify that the server exists
if (Dns.GetHostByName(server) == null) {
Console.WriteLine("Cannot find server: {0}", server);
return;
}
// Try to connect to the server
tcpc.Connect(server, 13);
// Get the stream
Stream s;
try {
s = tcpc.GetStream();
} catch (InvalidOperationException) {
Console.WriteLine("Cannot connect to server: {0}", server);
return;
}
// Read the stream and convert it to ASII
int bytes = s.Read(read, 0, read.Length);
String Time = Encoding.ASCII.GetString(read);
// Display the data
Console.WriteLine("Received {0} bytes", bytes);
Console.WriteLine("Current date and time is: {0}", Time);
tcpc.Close();
// Wait for user response to exit
Console.WriteLine("Press Return to exit");
Console.Read();
}
}
SERVER CODE
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Globalization;
class Server {
public static void Main() {
DateTime now;
String strDateLine;
Encoding ASCII = Encoding.ASCII;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
try
{
TcpListener tcpl = new TcpListener(13); // listen on port 13
tcpl.Start();
Console.WriteLine("Waiting for clients to connect");
Console.WriteLine("Press Ctrl+c to Quit...");
while (true) {
// Accept will block until someone connects
Socket s = tcpl.AcceptSocket();
// Get the current date and time then concatenate it
// into a string
now = DateTime.Now;
strDateLine = now.ToShortDateString() + " " + now.ToLongTimeString();
// Convert the string to a Byte Array and send it
Byte[] byteDateLine = ASCII.GetBytes(strDateLine.ToCharArray());
s.Send(byteDateLine, byteDateLine.Length, 0);
s.Close();
Console.WriteLine("Sent {0}", strDateLine);
}
}
catch (SocketException socketError)
{
if (socketError.ErrorCode == 10048)
{
Console.WriteLine("Connection to this port failed. There is another
server is listening on this port.");
}
}
}
}
|