Network Programming Code Questions
Network Programming Code Questions
Q0: Which namespaces must be imported to use the classes used in the above code?
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;
Q3: Write code to send an image from client to server using NetworkStream.
try
{
openFileDialog1.ShowDialog();
string mypic_path = openFileDialog1.FileName;
pictureBox1.Image = Image.FromFile(mypic_path);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] arrImage = ms.GetBuffer();
ms.Close();
TcpClient myclient = new TcpClient(txt_host.Text, 5020);
NetworkStream myns = myclient.GetStream();
BinaryWriter mysw = new BinaryWriter(myns);
mysw.Write(arrImage);
mysw.Close();
myns.Close();
myclient.Close();
}
catch(Exception ex){ MessageBox.Show(ex.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);
mysocket = mytcpl.AcceptSocket();
myns = new NetworkStream(mysocket);
pictureBox1.Image = Image.FromStream(myns);
mytcpl.Stop();
if(mysocket.Connected == true)
{
while(true)
{
Image_Receiver();
}
}
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)
{
try
{
mytcpl.Stop();
Application.Exit();
}
catch(Exception ex) { MessageBox.Show(ex.Message); }
}
Q6: Write code to save the received image from PictureBox to a JPEG file.
try
{
saveFileDialog1.Filter = "JPEG Image (*.jpg)|*.jpg";
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string mypic_path = saveFileDialog1.FileName;
pictureBox1.Image.Save(mypic_path);
}
}
catch(Exception)
{
}
Thread myth;
myth = new Thread(new System.Threading.ThreadStart(Image_Receiver));
myth.Start();