Course Info
Policies
Schedule
Homework
Labs
Exams
Lectures

TA Office hours

Gallery

CLIENT CODE

import System.*;
import System.Net.*;
import System.Net.Sockets.*;
import System.IO.*;
import System.Text.*;


class Client
{

public static void main(String[] args)
{
TcpClient tcpc = new TcpClient();
ubyte[] read = new ubyte[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
try
{
tcpc.Connect(server, 13);
}
catch(SocketException exc)
{
Console.WriteLine("Cannot connect to {0}: {1}", server, exc.get_Message());
return;
}

// Get the stream
Stream s;
try
{
s = tcpc.GetStream();
}
catch(InvalidOperationException exp)
{
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.get_ASCII().GetString(read);

// Display the data
Console.WriteLine("Received {0} bytes", (Int32)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();
} //Main
} //Client

 

SERVER CODE

import System.*;
import System.Net.*;
import System.Net.Sockets.*;
import System.Text.*;
import System.Threading.*;
import System.Globalization.*;


class Server
{

public static void main(String[] args)
{
DateTime now;
String strDateLine;
Encoding ASCII = Encoding.get_ASCII();

System.Threading.Thread.get_CurrentThread().set_CurrentCulture(CultureInfo.get_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.get_Now();
strDateLine = now.ToShortDateString() + " " + now.ToLongTimeString();

// Convert the string to a Byte Array and send it
ubyte[] byteDateLine = ASCII.GetBytes(strDateLine.ToCharArray());
s.Send(byteDateLine, byteDateLine.length, System.Net.Sockets.SocketFlags.None);
s.Close();
Console.WriteLine("Sent {0}", strDateLine);
}
}
catch(SocketException socketError)
{
if (socketError.get_ErrorCode() == 10048)
{
Console.WriteLine("Connection to this port failed. There is another server is listening on this port.");
}
}
} //Main
} //Server