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 [Link];
// Provides simple network functions
using [Link];
// Enables socket programming
using [Link];
// Provides I/O classes like Stream, BinaryWriter
using [Link];
// Provides encoding classes like ASCIIEncoding
using [Link];
// Enables multithreading support
Q1: Write code to send a message using TCP in C#.
String str = [Link]();
// Read user input from console
ASCIIEncoding asen = new ASCIIEncoding();
// Create ASCII encoding object
byte[] ba = [Link](str);
// Convert string to byte array
TcpClient tcpclnt = new TcpClient("[Link]", 8001);
// Connect to server at specified IP and port
NetworkStream mynetsream = [Link]();
// Obtain network stream from TCP client
StreamWriter myswrite = new StreamWriter(mynetsream);
// Create StreamWriter to write to network stream
[Link]("Your Message");
// Send message over network
[Link]();
// Close network stream
[Link]();
// 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
[Link]();
// Start listening for incoming connections
Socket s = [Link]();
// 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
[Link]([Link]());
// Read incoming message and write to console
[Link]();
// Close the socket
Q3: Write code to send an image from client to server using NetworkStream.
try
// Begin try block to catch exceptions
{
[Link]();
// Open file dialog to select image
string mypic_path = [Link];
// Get selected file path
[Link] = [Link](mypic_path);
// Load image into PictureBox
MemoryStream ms = new MemoryStream();
// Create MemoryStream to hold image data
[Link](ms, [Link]);
// Save image into MemoryStream in its raw format
byte[] arrImage = [Link]();
// Get byte array from MemoryStream
[Link]();
// Close MemoryStream
TcpClient myclient = new TcpClient(txt_host.Text, 5020);
// Connect to server using host text and port 5020
NetworkStream myns = [Link]();
// Obtain network stream from TCP client
BinaryWriter mysw = new BinaryWriter(myns);
// Create BinaryWriter to write binary data to network stream
[Link](arrImage);
// Send image byte array over network
[Link]();
// Close BinaryWriter
[Link]();
// Close network stream
[Link]();
// Close TCP connection
}
catch(Exception ex){ [Link]([Link]); }
// 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 = [Link]();
// Accept incoming connection as a socket
myns = new NetworkStream(mysocket);
// Wrap socket in a NetworkStream
[Link] = [Link](myns);
// Load image directly from network stream into PictureBox
[Link]();
// Stop listening (close TCP listener)
if([Link] == 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,
[Link] e) // Event handler for form closing
{
try
// Begin try block to catch exceptions
{
[Link]();
// Stop the TCP listener
[Link]();
// Exit the application
}
catch(Exception ex) { [Link]([Link]); }
// 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
{
[Link] = "JPEG Image (*.jpg)|*.jpg";
// Set file dialog filter to JPEG files
if([Link]() == [Link])
// If user selects OK in save dialog
{
string mypic_path = [Link];
// Get chosen file path
[Link](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 [Link];
// Import threading namespace
Thread myth;
// Declare a Thread variable
myth = new Thread(new [Link](Image_Receiver));
// Initialize thread to run Image_Receiver method
[Link]();
// Start the thread
Q8: Write updated Form1_Closing event code to stop the thread.
private void Form1_Closing(object sender,
[Link] e) // Event handler for form closing
{
try
// Begin try block
{
[Link]();
// Stop the TCP listener
[Link]();
// Abort the image-receiving thread
}
catch(Exception ex) { [Link]([Link]); }
// Catch and show any exception message
}
Q9: Write code to send a message using UDP Multicast.
Socket server = new Socket([Link], [Link],
[Link]); // Create a UDP socket
IPEndPoint iep = new IPEndPoint([Link]("[Link]"), 5020);
// Define multicast group IP and port
byte[] data = [Link]("This is a test message");
// Convert message string to byte array using ASCII encoding
[Link](data, iep);
// Send UDP packet to multicast group
[Link]();
// Close the socket
Q10: Write code to receive a UDP Multicast message.
UdpClient sock = new UdpClient(5020);
// Create UDP client listening on port 5020
[Link]([Link]("[Link]"), 50);
// Join multicast group with TTL 50
IPEndPoint iep = new IPEndPoint([Link], 0);
// Prepare endpoint to receive data
byte[] data = [Link](ref iep);
// Receive data from multicast group
string stringData = [Link](data, 0, [Link]);
// Convert received bytes back to string
[Link]("received: {0} from: {1}", stringData, [Link]());
// Print received message and sender info
[Link]();
// Close the UDP client