The lab of this week and the following two weeks will not use Wireshark but focu
ID: 3793031 • Letter: T
Question
The lab of this week and the following two weeks will not use Wireshark but focus on socket programming using C#.
It's strongly suggested that, before doing this lab, you review Module 3 contents about socket programming, which is covered in 2.7 of Chapter 2.
Once you download the above two C# programs, compile them first. Using the simple C# command line compiler (like we did in the lab of Module 2) is recommended. You can use Visual Studio but only if you know how to manipulate that tool.
Then, execute the server.exe first in one command prompt, and execute the client.exe in another command prompt as shown below:
The purpose of this lab is to learn the communication, especially the handshaking process between a client and a server using a socket. Normally clients and the server are programs running in different computers in a network. This lab wants to keep the setting simple, so both client and server run in the same computer using the special loopback (or localhost) IP address, 127.0.0.1. In this case, a router is not needed. If you want, you may change it to a real IP address of your computer and let your router help to connect them together.
When you complete 1 to 4 as shown in the above figure, you may enter a message like "Hello, this is CNT4104 lab!!". Once you hit the Enter key, watch both screen: the server screen will display "Message of client received" followed by the received message. Then, it prompts to you "Hit 'Enter' to send acknowledgement to clicnt and end the session...." In the mean while, the client screen shows "Transmitting.....".
If you click on the server screen and hit Enter key, it sends an acknowledgement to client and close the socket and session. When the client gets the confirmation, it also close its session automatically.
You may repeat the execution of both program to get familiar with the process of their handshaking.
Both programs contain detailed comments to help you read and trace their code. In the server.cs, the most important classes are TcpListener and Socket. A TcpListener object can use Start() (in line 35) and Stop() (in line 74) to begin and end listening if any client requests to connect. It uses AcceptSocket() (in line 41) to accept a client request and make a scocket. Once instantiated, a Socket object uses Receive() (in line 48) and Send() (in line 62) to communicate with the client.
Similarly, in the client.cs, the key class is TcpClient. A TcpClient object requests to connect to a server by using Connect() (in line 28). It must call its GetStream() (in line 40) in order to get a NetworkStream object to set up a input/output stream. Then, the stream object can use its Write() (in line 42) and Read() (in line 46) to communicate with the server.
Note that, when data or message is transmitted via a stream, it is done byte by byte. That's why the input message is converted and stored in line 35 of client.cs in a byte array to allow the stream object to access each byte. Similarly, when the stream reads all bytes from the server, each byte is converted back to a character in line 52 and displayed in console.
You should see exactly the same in server.cs. When it receives client's message, it is stored in a byte array in line 48 and each byte is converted to a character in line 54 to display in console. Later in line 62, it converts each character of the confirmation message into a byte and sends to client, byte by byte.
*To learn more about TcpListener, TcpClient, and Socket, or any classes in the programs, you may reference MSDN library directly at https://msdn.microsoft.com/en-us/library/ (Links to an external site.) where you enter a keyword or class name or method name in a Search box to get the related pages, or simply google the term for more details.
-------------------------------------------------------------------------------------server.cs-----------------------------------------------------------------------------------------------------
/*
* C# Program to Establish Client Server Relationship
*/
//SERVER PROGRAM
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace MyServer4104
{
class Program
{
static void Main(string[] args)
{
//Declare the server queue:
TcpListener serverQueue = null;
try
{
// 1. Set up an IP object to represent one IP of your computer:
IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //Or the wired or WiFi IP of your computer
// 2. Create the queue to listen for and accept incoming connection requests:
serverQueue = new TcpListener(ipAd, 63000);
// TCP port numbers range from 0 to 65536, i.e., 16 bits.
// DO NOT use a port number in the range from 0 to 1023. They are the well-known ports or
// system ports.
// Port numbers from 1024 to 49151 are the registered ports. You may use them like 63000
// if they are not registered or registered but the program is not running in your computer.
// Use the Start method to begin listening for incoming connection requests.
// It will queue incoming connections until the Stop method is called.
serverQueue.Start();
Console.WriteLine("[Server] The server is running at port 63000");
Console.WriteLine("[Server] So, the server's local end point is: " + serverQueue.LocalEndpoint);
Console.WriteLine("[Server] Waiting for a client's connection........");
// 3. Pull a connection from the queue to make a socket:
Socket aSocket = serverQueue.AcceptSocket();
Console.WriteLine(" [Server] Connection accepted from a client " +
"whose end point is: " + aSocket.RemoteEndPoint);
// 4. Get the message sent by client through socket:
byte[] incomingDataBuffer = new byte[1000];
char aChar = new char();
int totalBytes = aSocket.Receive(incomingDataBuffer); // Receive from client, byte by byte
// 5. Display the received message:
Console.WriteLine("[Server] Message of client recieved");
for (int i = 0; i < totalBytes; i++)
{
aChar = Convert.ToChar(incomingDataBuffer[i]);
Console.Write(aChar);
}
// 6. Tell client its message was received:
ASCIIEncoding ascii = new ASCIIEncoding();
Console.Write(" [Server] Hit 'Enter' to send acknowledgement to clicnt and end the session....");
Console.ReadLine();
aSocket.Send(ascii.GetBytes("[Server] Your message was recieved.")); // Send to client, byte by byte through socket
aSocket.Close();
}
catch (SocketException se)
{
Console.WriteLine(" [Server] Socket Error Code: " + se.ErrorCode.ToString());
Console.WriteLine(" " + se.StackTrace);
}
finally
{
// 7. Stop listening request and recycle the queue:
serverQueue.Stop();
Console.WriteLine(" Bye!");
}
}
}
}
-------------------------------------------------------------------------------------------------client.cs---------------------------------------------------------------------------------------------------------------------------
/*
* C# Program to Establish Client Server Relationship
*/
//CLIENT PROGRAM
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace MyClient4104
{
class Program
{
static void Main(string[] args)
{
try
{
// 1. Create an object to represent the client:
TcpClient myClient = new TcpClient();
// 2. Connect this client to a server:
// Note: for this client to work there must be already a server connected to
// the same IP address and port combination.
Console.WriteLine("[Client] Connecting to server.....");
myClient.Connect("127.0.0.1", 63000); //192.168.0.3
Console.WriteLine("[Client] Server is connected");
// 3. Capture a message from keyboard and store it in a byte array:
Console.Write("[Client] Enter a message for server: ");
String aMessage = Console.ReadLine();
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] messageBytes = ascii.GetBytes(aMessage);
// 4. The GetStream method of a TcpClient object, myClient, returns a NetworkStream object,
// which inherits from the Stream class. NetworkStream has methods to send (using Write())
// and receive (using Read()) data in network communications.
Stream aStream = myClient.GetStream();
Console.WriteLine("[Client] Transmitting.....");
aStream.Write(messageBytes, 0, messageBytes.Length); // Write() to server
// 5. Stand by to listen if server send an acknowledge back:
byte[] serverMessageBytes = new byte[500];
int totalBytes = aStream.Read(serverMessageBytes, 0, 500); // Read() from server
// 6. Display server's message
char aChar = new char();
for (int i = 0; i < totalBytes; i++)
{
aChar = Convert.ToChar(serverMessageBytes[i]);
Console.Write(aChar); // Display one character to command prompt
}
// 7. Stop the client and recycle the TcpClient object:
myClient.Close();
Console.WriteLine(" Bye!");
}
catch (SocketException se)
{
Console.WriteLine(" [Client] Socket Error Code: " + se.ErrorCode.ToString());
Console.WriteLine(" " + se.StackTrace);
}
}
}
}
Explanation / Answer
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace MyClient4104
{
class Program
{
static void Main(string[] args)
{
try
{
// 1. Create an object to represent the client:
TcpClient myClient = new TcpClient();
// 2. Connect this client to a server:
// Note: for this client to work there must be already a server connected to
// the same IP address and port combination.
Console.WriteLine("[Client] Connecting to server.....");
myClient.Connect("127.0.0.1", 63000); //192.168.0.3
Console.WriteLine("[Client] Server is connected");
// 3. Capture a message from keyboard and store it in a byte array:
Console.Write("[Client] Enter a message for server: ");
String aMessage = Console.ReadLine();
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] messageBytes = ascii.GetBytes(aMessage);
// 4. The GetStream method of a TcpClient object, myClient, returns a NetworkStream object,
// which inherits from the Stream class. NetworkStream has methods to send (using Write())
// and receive (using Read()) data in network communications.
Stream aStream = myClient.GetStream();
Console.WriteLine("[Client] Transmitting.....");
aStream.Write(messageBytes, 0, messageBytes.Length); // Write() to server
// 5. Stand by to listen if server send an acknowledge back:
byte[] serverMessageBytes = new byte[500];
int totalBytes = aStream.Read(serverMessageBytes, 0, 500); // Read() from server
// 6. Display server's message
char aChar = new char();
for (int i = 0; i < totalBytes; i++)
{
aChar = Convert.ToChar(serverMessageBytes[i]);
Console.Write(aChar); // Display one character to command prompt
}
// 7. Stop the client and recycle the TcpClient object:
myClient.Close();
Console.WriteLine(" Bye!");
}
catch (SocketException se)
{
Console.WriteLine(" [Client] Socket Error Code: " + se.ErrorCode.ToString());
Console.WriteLine(" " + se.StackTrace);
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.