using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;


namespace receiver
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Thread thr;
        TcpListener tcpl;
        NetworkStream ns;
        Socket mySocket;


        private void Form1_Load(object sender, EventArgs e)
        {
            thr = new Thread(new ThreadStart(Receiver));
            thr.Start();
        }

        private void Receiver()
        {
            do
            {
                tcpl = new TcpListener(7000);
                tcpl.Start();
                mySocket = tcpl.AcceptSocket();
                ns = new NetworkStream(mySocket);
                BinaryFormatter bf = new BinaryFormatter();
                object filename = bf.Deserialize(ns);

                BinaryReader br = new BinaryReader(ns);

                byte[] buffer = br.ReadBytes(5000000);

                FileStream fs = new FileStream(txtSavePath.Text + (string)filename, FileMode.CreateNew, FileAccess.Write);
                fs.Write(buffer, 0, buffer.Length);

                fs.Close();
                tcpl.Stop();

                CheckForIllegalCrossThreadCalls = false;
                listBox1.Items.Add("new file received. Saved into " + txtSavePath.Text);
                
            } while (true);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            thr.Abort();
        }
    }
}
