Not logged in. · Lost password · Register
Forum: agsXMPP RSS
Avatar
DYLAN1988 #1
Member since Jul 2007 · 3 posts
Group memberships: Members
Show profile · Link to this post
Subject: File Transfer HELP*
I'm writting an application for file transfer in C# language (client send file to server)
and there are so many problems in my application.
anyone can help me with it please?

namespace CommunicationServer
{
    public partial class Form1 : Form
    {
        private TcpListener tlsServer;
        private Thread threadDownload;
        private delegate void UpdateStatusCallback(string StatusMessage);
        private delegate void UpdateProgressCallback(Int64 BytesRead, Int64 TotalBytes);
        private static int PercentProgress;
        private string CurrentPath;
        private Bitmap MyImage;

        public Form1()
        {
            InitializeComponent();
            textBoxIP.Text = GetIP();
            ProcessFolder();
            listFileItems.SelectedIndexChanged +=
                new EventHandler(OnlistFileItemSelected);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            threadDownload = new Thread(StartReceiving);
            threadDownload.Start();
        }

        public void StartReceiving()
        {
            if (textBoxPort.Text == "")
            {
                MessageBox.Show("Please enter a Port Number");
                return;
            }

            string portStr = textBoxPort.Text;
            int port = System.Convert.ToInt32(portStr);

            tlsServer = new TcpListener(IPAddress.Any, port);
            tlsServer.Start();
            this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Server starts listening." });
           
            try
            {
                Byte[] bytes = new Byte[2048];
                String data = null;
                while (true)
                {
                    TcpClient client = tlsServer.AcceptTcpClient();
                    this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Connected!" });
                    NetworkStream stream = client.GetStream();

                    int i;
                    data = null;
                    try
                    {
                        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                            this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Received: " + data });
                            data = data.ToUpper();
                            byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
                            stream.Write(msg, 0, msg.Length);
                            this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "Sent: " + data });
                        }
                    }
                    catch (Exception ex)
                    {
                         this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { ex.Message  });
                    }
                    client.Close();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { "The file has been received. Closing streams." });

            }
            tlsServer.Stop();
        }

        private void UpdateStatus(string StatusMessage)
        {
            textBoxStatus.Text += StatusMessage;
        }

        private void updateControls(bool listening)
        {
            buttonStart.Enabled = !listening;
            buttonStop.Enabled = listening; ;
        }

        private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
        {
            if (TotalBytes > 0)
            {
                PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
                prgDownload.Value = PercentProgress;
            }
        }

        protected void OnlistFileItemSelected(object Sender, EventArgs e)
        {
            string SelectedString = listFileItems.SelectedItem.ToString();
            string FullPathName = Path.Combine(CurrentPath, SelectedString);
            ProcessFile(FullPathName);
            ShowImage(FullPathName, 196, 188);
        }

        public void ShowImage(string fileToDisplay, int xsize, int ysize)
        {
            if (MyImage != null)
            {
                MyImage.Dispose();
            }
            MyImage = new Bitmap(fileToDisplay);
            imageBox.ClientSize = new Size(xsize, ysize);
            imageBox.Image = (Image)MyImage;
        }

        protected void ProcessFolder()
        {
            try
            {
                DirectoryInfo TheFolder = new DirectoryInfo(@"D:\serverReceive");
                if (TheFolder.Exists)
                {
                    ListContentsOfFolder(TheFolder);
                    return;
                }
                TheFolder.Create();
                ListContentsOfFolder(TheFolder);
            }
            finally { }
        }

        protected void ProcessFile(string PathName)
        {
            try
            {
                FileInfo currentFile = new FileInfo(PathName);
                if (currentFile.Exists)
                {
                    return;
                }
                throw new FileNotFoundException();
            }
            catch (FileNotFoundException)
            {
                textBoxDir.Text = PathName;
            }
            catch (Exception e)
            {
                textBoxDir.Text = PathName;
                listFileItems.Items.Add("Error Processing");
                listFileItems.Items.Add(e.Message);
            }
        }

        protected void ListContentsOfFolder(DirectoryInfo Parent)
        {
            CurrentPath = Parent.FullName;
            textBoxDir.Text = CurrentPath;

            foreach (FileInfo NextFile in Parent.GetFiles())
            {
                if (NextFile.Extension == ".jpg" || NextFile.Extension == ".JPG" ||
                    NextFile.Extension == ".jpeg" || NextFile.Extension == ".JPEG" ||
                    NextFile.Extension == ".gif" || NextFile.Extension == ".GIF" ||
                    NextFile.Extension == ".png" || NextFile.Extension == ".PNG" ||
                    NextFile.Extension == ".bmp" || NextFile.Extension == ".BMP" ||
                    NextFile.Extension == ".tif" || NextFile.Extension == ".TIF" ||
                    NextFile.Extension == ".tiff" || NextFile.Extension == ".TIFF")
                {
                    listFileItems.Items.Add(NextFile.Name);
                }
            }

        }

        String GetIP()
        {
            String strHostName = Dns.GetHostName();

            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

            String IPStr = "";
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            tlsServer.Stop();
            textBoxStatus.Text = "Server stops listening";
        }
    }
}
Avatar
DYLAN1988 #2
Member since Jul 2007 · 3 posts
Group memberships: Members
Show profile · Link to this post
and the client application..

namespace CommunicationClient
{
    public partial class Form1 : Form
    {
        private string CurrentParentPath;
        private Bitmap MyImage;
        TcpClient tcpClient;
        FileStream fstFile;
        NetworkStream strRemote;
        private string FullPathName;

        public Form1()
        {
            InitializeComponent();

            textBoxIP.Text = GetIP();
            ProcessFolder(@"D:\pictures");

            listFileItems.SelectedIndexChanged +=
                new EventHandler(OnlistFileItemSelected);

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void ConnectToServer(string ServerIP, int ServerPort)
        {
            tcpClient = new TcpClient();

            if (textBoxIP.Text == "" || textBoxPort.Text == "")
            {
                MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
                return;
            }

            try
            {
                tcpClient.Connect(ServerIP, ServerPort);
                textBoxStatus.Text = "Connected";
            }
            catch (Exception em)
            {
                textBoxStatus.Text = em.Message;
            }
        }

        protected void OnlistFileItemSelected(object Sender, EventArgs e)
        {
            string SelectedString = listFileItems.SelectedItem.ToString();
            FullPathName = Path.Combine(CurrentParentPath, SelectedString);
            ProcessFile(FullPathName);
            ShowImage(FullPathName, 196, 188);
        }

        public void ShowImage(string fileToDisplay, int xsize, int ysize)
        {
            if (MyImage != null)
            {
                MyImage.Dispose();
            }
            MyImage = new Bitmap(fileToDisplay);
            imageBox.ClientSize = new Size(xsize, ysize);
            imageBox.Image = (Image)MyImage;
        }

        protected void ProcessFolder(string PathName)
        {
            try
            {
                ClearAllFields();
                DirectoryInfo TheFolder = new DirectoryInfo(PathName);
                if (TheFolder.Exists)
                {
                    ListContentsOfFolder(TheFolder);
                    return;
                }

                throw new FileNotFoundException();
            }
            catch (FileNotFoundException)
            {
                textBoxDir.Text = PathName;
            }

        }

        protected void ProcessFile(string PathName)
        {
            try
            {
                FileInfo currentFile = new FileInfo(PathName);
                if (currentFile.Exists)
                {
                    DisplayFileInfo(currentFile);
                    return;
                }
                throw new FileNotFoundException();
            }
            catch (FileNotFoundException)
            {
                textBoxDir.Text = PathName;
            }
            catch (Exception e)
            {
                textBoxDir.Text = PathName;
                listFileItems.Items.Add("Error Processing");
                listFileItems.Items.Add(e.Message);
            }
        }

        protected void DisplayFileInfo(FileInfo currentFile)
        {
            textBoxName.Text = currentFile.Name;
            textBoxCreated.Text = currentFile.CreationTime.ToLongTimeString();
            textBoxSize.Text = currentFile.Length.ToString() + " Bytes";
        }

        protected void ListContentsOfFolder(DirectoryInfo Parent)
        {
            CurrentParentPath = Parent.FullName;
            textBoxDir.Text = CurrentParentPath;

            foreach (FileInfo NextFile in Parent.GetFiles())
            {
                if (NextFile.Extension == ".jpg" || NextFile.Extension == ".JPG" ||
                    NextFile.Extension == ".jpeg" || NextFile.Extension == ".JPEG" ||
                    NextFile.Extension == ".gif" || NextFile.Extension == ".GIF" ||
                    NextFile.Extension == ".png" || NextFile.Extension == ".PNG" ||
                    NextFile.Extension == ".bmp" || NextFile.Extension == ".BMP" ||
                    NextFile.Extension == ".tif" || NextFile.Extension == ".TIF" ||
                    NextFile.Extension == ".tiff" || NextFile.Extension == ".TIFF")
                {
                    listFileItems.Items.Add(NextFile.Name);
                }
            }
        }

        public void ClearAllFields()
        {
            textBoxName.Text = "";
            textBoxCreated.Text = "";
            textBoxSize.Text = "";
        }

        String GetIP()
        {
            String strHostName = Dns.GetHostName();
            IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
            String IPStr = "";
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            if (textBoxIP.Text == "" || textBoxPort.Text == "")
            {
                MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
                return;
            }
            ConnectToServer(textBoxIP.Text, Convert.ToInt32(textBoxPort.Text));
        }

        private void buttonDisconnect_Click(object sender, EventArgs e)
        {
            tcpClient.Close();
            strRemote.Close();
            fstFile.Close();
            textBoxStatus.Text = "Disconnected from server. \r\n";

        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            if (tcpClient != null)
            {
                tcpClient.Close();
            }
            Close();
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (tcpClient != null)
                {       
                    byte[] byteSend = new byte[tcpClient.ReceiveBufferSize];
                    strRemote = tcpClient.GetStream();
                    strRemote.Write(byteSend, 0, byteSend.Length);
                    byteSend = new Byte[2048];
                    String responseData = String.Empty;

                    ASCIIEncoding ASCII = new ASCIIEncoding();

                    // Read the first batch of the TcpServer response bytes.
                    Int32 bytes = strRemote.Read(byteSend, 0, byteSend.Length);
                    //responseData = System.Text.Encoding.ASCII.GetString(byteSend, 0, bytes);
                    responseData = ASCII.GetString(byteSend, 0, byteSend.Length);
                    textBoxStatus.Text = "Received: " + responseData;

                    // Close everything.
                    strRemote.Close();
                    tcpClient.Close();
                }
            }
            catch (ObjectDisposedException em)
            {
                    textBoxStatus.Text = em.Message;
               
            }
               
        }
    }
}
Avatar
Alex #3
Member since Feb 2003 · 4447 posts · Location: Germany
Group memberships: Administrators, Members
Show profile · Link to this post
Hello,

i have no idea how we can help you. You posted lots of code but no description of your problem.

Alex
Avatar
DYLAN1988 #4
Member since Jul 2007 · 3 posts
Group memberships: Members
Show profile · Link to this post
i managed to established connection between server and client.
but when i send a file, it did not manage to send over.
i tried a couple of times and the following errors were shown:

Server Side: unable to read data from the transport connection: An established connection was aborted by the software in your host machine.

Client Side: "Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'."

Client is the sender and Server is the receiver.
Close Smaller – Larger + Reply to this post:
Verification code: VeriCode Please enter the word from the image into the text field below. (Type the letters only, lower case is okay.)
Smileys: :-) ;-) :-D :-p :blush: :cool: :rolleyes: :huh: :-/ <_< :-( :'( :#: :scared: 8-( :nuts: :-O
Special characters:
Forum: agsXMPP RSS