1. CSC 469/569 LAB / HOMEWORK 4: EXPLORING .NET
SOCKET PROGRAMMING
PROF. GODFREY C. MUGANDA
The goal of this homework is to allow you to extend what we have learned in class
to acquire on your own, skills that are related to skills you already have. You
will figure out, using online resources, how to do socket programming on the .NET
platform using C#. This lab is an outline of how you should go about acquiring
these skills.
1. Learn the Visual Studio IDE for C#
Open Visual Studio 2008, then File/New/ Project. You need to select a project
type. First, in the Project Types pane on the left, select Visual C# (You may have
to look under “Other Languages” if the IDE is already set up for Visual C++ or
Visual Basic. Make sure you select a Console Application on the right. At the
botton, specify a name for your application, and make sure you are saving your
project on the local C drive. (Visual Studio hates Network Drives.) Click Ok, fill
in some code to get the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Muganda for President.");
}
}
}
Compile by using Build Solution on the Build menu, and run by using Start WIthout
Debugging on the Debug menu.
2. Glance over C# Syntax
C# is so similar to Java it is ridiculous. Glance over the following articles in the
Visual Studio 2008 Documentation, found off the Visual Studio 2008 menu off of
the Windows Start menu. Look under Development Tools and Languages, then
look under Visual Studio, then look under Visual C#.
1
2. 2 PROF. GODFREY C. MUGANDA
Under Visual C#, look at Getting Started with Visual C#, C# Programming
Guide, Visual C# Guided Tour/C# Language Primer.
You do not need to spend a lot of time on these: you just need to familiarize yourself
with the documentation so you know where to look if you need information.
3. Write .NET Server
Look up information on the TcpListener class, which is almost the equivalent of
a Java ServerSocket class. There is also a TcpClient class, which is almost the
counterpart of the Java Socket class. The .NET Documentation has examples
of the use of most of these classes. Here is one, taken from the Visual Studio
documentation.
C# Copy Code
/**
* The following sample is intended to demonstrate how to use a
* TcpListener for synchronous communcation with a TCP client
* It creates a TcpListener that listens on the specified port (13000).
* Any TCP client that wants to use this TcpListener has to explicitly connect
* to an address obtained by the combination of the server
* on which this TcpListener is running and the port 13000.
* This TcpListener simply echoes back the message sent by the client
* after translating it into uppercase.
* Refer to the related client in the TcpClient class.
*/
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class TcpListenerSample
{
static void Main(string[] args)
{
try
{
// set the TcpListener on port 13000
int port = 13000;
TcpListener server = new TcpListener(IPAddress.Any, port);
// Start listening for client requests
server.Start();
// Buffer for reading data
byte[] bytes = new byte[1024];
string data;
//Enter the listening loop
while (true)
3. CSC 469/569 LAB / HOMEWORK 4: EXPLORING .NET SOCKET PROGRAMMING 3
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
i = stream.Read(bytes, 0, bytes.Length);
while (i != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(String.Format("Received: {0}", data));
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine(String.Format("Sent: {0}", data));
i = stream.Read(bytes, 0, bytes.Length);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("Hit enter to continue...");
Console.Read();
}
}
The idea is that a TcpListener has an AcceptTcpClient or AcceptSocket method
that returns either a Socket or a TcpClient. This Socket or TcpClient will be
connected to a remote Socket or TcpClient. Thus the actual work on the server
end is done by a TcpClient on the server side talking to another TcpClient on the
client side.
This example uses classes we have not discussed. Look them up. For example,
look up the NetworkStream class. This is returned by the getStream() method on
a TcpClient or a Socket. This class is a binary stream that can be both read and
written. The example above treats it as a binary stream by reading and writing
bytes to it.
If you want to use the NetworkStream as a character stream, you can put StreamReader
and StreamWriter on top of the NetworkStream object, as shown here:
myNetworkStream = New NetworkStream(mySocket)
reader = New StreamReader(myNetworkStream)
4. 4 PROF. GODFREY C. MUGANDA
writer = New StreamWriter(myNetworkStream)
writer.AutoFlush = True
This is just like good old Java, where we put an InputStreamReader on top of an
byte stream to convert it to a character stream, and where we use a PrintWriter
with the auto flush property on top of a byte output stream. Truly, there is nothing
new under the sun, and you should feel right at home.
4. Run your Server
You can run your server from the IDE, or you can run it from the command line.
To run a server from the command line, Start the Visual Studio 2008 command
box from the Visual Studio Tools menu off of the Visual Studion menu. Then use
cd to change directory to the folder that contains your executable and run it from
the commandline.
To test your server, just use good old Telnet or Putty.
5. Write your Client
Read the documentation for the TcpClient and Socket classes to figure out how
to write a client, or look for an example in the documentation or online.
6. What to submit
Write .NET server and client that does arithmetic. The server is iterative, so it
uses no threads and it handles on client at a time. A client connects and sends
messages that look like this:
add 23 5
mult 4 12
bye
Any number of messages can be sent, but the server closes the connection as soon
as it gets a bye from the client. For all the other messages, the server returns
a number that is either the sum or the product of the two numbers sent in the
message.
The client will be a console application that just reads commands from the user and
sends them over to the server. To help you with the client, Here is a simple program
that illustrates how to read numbers from the console. Actually your program will
read entire strings. The client can just send the entire string to the server without
bothering to parse it. The server will have to parse it to extract the numbers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetApp
{
class Program
{
static void Main(string[] args)
5. CSC 469/569 LAB / HOMEWORK 4: EXPLORING .NET SOCKET PROGRAMMING 5
{
int a, b;
System.Console.Title = "Muganda’s Console Input Program";
String input;
while (true)
{
System.Console.Write("Enter a number: ");
input = System.Console.ReadLine();
if (input == "bye") break;
a = int.Parse(input.Trim());
System.Console.Write("Enter another number: ");
input = System.Console.ReadLine();
b = int.Parse(input.Trim());
System.Console.WriteLine("The sum of {0} and {1} is {2}", a, b, a + b);
}
}
}
}
7. Miscellaneous Hints
You may find the .NET String.Format class and String.Split class useful.