Network Programming Questions and Answers
Q0: Which namespaces must be imported to use the classes used in the above
code?
using System;
// Base namespace
using System.Net;
// Provides simple network functions
using System.Net.Sockets;
// Enables socket programming
using System.IO;
// Provides I/O classes like Stream, BinaryWriter
using System.Text;
// Provides encoding classes like ASCIIEncoding
using System.Threading;
// Enables multithreading support
Q1: Write code to send a message using TCP in C#.
String str = Console.ReadLine();
// Read user input from console
ASCIIEncoding asen = new ASCIIEncoding();
// Create ASCII encoding object
byte[] ba = asen.GetBytes(str);
// Convert string to byte array
TcpClient tcpclnt = new TcpClient("192.168.0.2", 8001);
// Connect to server at specified IP and port
NetworkStream mynetsream = tcpclnt.GetStream();
// Obtain network stream from TCP client
StreamWriter myswrite = new StreamWriter(mynetsream);
// Create StreamWriter to write to network stream
myswrite.WriteLine("Your Message");
// Send message over network
mynetsream.Close();
// Close network stream
tcpclnt.Close();
// Close TCP connection
Q2: Write code to receive a message on the server using TCP.
TcpListener myList = new TcpListener(5020);
// Initialize TCP listener on port 5020
myList.Start();
// Start listening for incoming connections
Socket s = myList.AcceptSocket();
// Accept an incoming connection and return a socket
NetworkStream myns = new NetworkStream(s);
// Wrap the socket in a NetworkStream
StreamReader mysr = new StreamReader(myns);
// Create StreamReader to read from the network stream
Console.Write(mysr.ReadLine());
// Read incoming message and write to console
s.Close();
// Close the socket
Q3: Write code to send an image from client to server using NetworkStream.
try
// Begin try block to catch exceptions
{
openFileDialog1.ShowDialog();
// Open file dialog to select image
string mypic_path = openFileDialog1.FileName;
// Get selected file path
pictureBox1.Image = Image.FromFile(mypic_path);
// Load image into PictureBox
MemoryStream ms = new MemoryStream();
// Create MemoryStream to hold image data
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
// Save image into MemoryStream in its raw format
byte[] arrImage = ms.GetBuffer();
// Get byte array from MemoryStream
ms.Close();
// Close MemoryStream
TcpClient myclient = new TcpClient(txt_host.Text, 5020);
// Connect to server using host text and port 5020
NetworkStream myns = myclient.GetStream();
// Obtain network stream from TCP client
BinaryWriter mysw = new BinaryWriter(myns);
// Create BinaryWriter to write binary data to network stream
mysw.Write(arrImage);
// Send image byte array over network
mysw.Close();
// Close BinaryWriter
myns.Close();
// Close network stream
myclient.Close();
// Close TCP connection
}
catch(Exception ex){ MessageBox.Show(ex.Message); }
// Catch and show any exception message
Q4: Write server-side code to receive the image sent by the client and display it
in a PictureBox.
TcpListener mytcpl = new TcpListener(5000);
// Initialize TCP listener on port 5000
mysocket = mytcpl.AcceptSocket();
// Accept incoming connection as a socket
myns = new NetworkStream(mysocket);
// Wrap socket in a NetworkStream
pictureBox1.Image = Image.FromStream(myns);
// Load image directly from network stream into PictureBox
mytcpl.Stop();
// Stop listening (close TCP listener)
if(mysocket.Connected == true)
// Check if socket is still connected
{
while(true)
// Loop to continuously receive images
{
Image_Receiver();
// Recursively call Image_Receiver to handle next image
}
Q5: Write the Form1_Closing event to stop the TCP listener and exit the
application.
private void Form1_Closing(object sender,
System.ComponentModel.CancelEventArgs e) // Event handler for form closing
{
try
// Begin try block to catch exceptions
{
mytcpl.Stop();
// Stop the TCP listener
Application.Exit();
// Exit the application
}
catch(Exception ex) { MessageBox.Show(ex.Message); }
// Catch and show any exception message
}
Q6: Write code to save the received image from PictureBox to a JPEG file.
try
// Begin try block to catch exceptions
{
saveFileDialog1.Filter = "JPEG Image (*.jpg)|*.jpg";
// Set file dialog filter to JPEG files
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
// If user selects OK in save dialog
{
string mypic_path = saveFileDialog1.FileName;
// Get chosen file path
pictureBox1.Image.Save(mypic_path);
// Save image from PictureBox to specified path
}
catch(Exception)
// Catch any exception (silently ignore)
{
}
Q7: Write code to use a Thread to receive the image.
using System.Threading;
// Import threading namespace
Thread myth;
// Declare a Thread variable
myth = new Thread(new System.Threading.ThreadStart(Image_Receiver));
// Initialize thread to run Image_Receiver method
myth.Start();
// Start the thread
Q8: Write updated Form1_Closing event code to stop the thread.
private void Form1_Closing(object sender,
System.ComponentModel.CancelEventArgs e) // Event handler for form closing
{
try
// Begin try block
{
mytcpl.Stop();
// Stop the TCP listener
myth.Abort();
// Abort the image-receiving thread
}
catch(Exception ex) { MessageBox.Show(ex.Message); }
// Catch and show any exception message
}
Q9: Write code to send a message using UDP Multicast.
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp); // Create a UDP socket
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 5020);
// Define multicast group IP and port
byte[] data = Encoding.ASCII.GetBytes("This is a test message");
// Convert message string to byte array using ASCII encoding
server.SendTo(data, iep);
// Send UDP packet to multicast group
server.Close();
// Close the socket
Q10: Write code to receive a UDP Multicast message.
UdpClient sock = new UdpClient(5020);
// Create UDP client listening on port 5020
sock.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 50);
// Join multicast group with TTL 50
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
// Prepare endpoint to receive data
byte[] data = sock.Receive(ref iep);
// Receive data from multicast group
string stringData = Encoding.ASCII.GetString(data, 0, data.Length);
// Convert received bytes back to string
Console.WriteLine("received: {0} from: {1}", stringData, iep.ToString());
// Print received message and sender info
sock.Close();
// Close the UDP client