There are two C# projects: one project is for the client, the other one is for the server. First step is to run the server , then to choose a target folder, after that to run the client project, to choose some text.txt to send to the server's target folder. Only client can send files to the server
Demo:
1.choosing file target 2.client sends
+------------+
| tar folder | <---------------- text.txt
+------------+
This works fine, but I want it to send the text.txt automatically every few minutes so I added while(true)
loop and Thread.Sleep(10000)
but it alaway gives Exceptions. I mean, It's not gives me to send it more then once.
Here the in client class I'm trying to put a while loop :
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)//browse btn
{
string n;
byte[] b1;
TcpClient client;
OpenFileDialog op;
Stream s;
StreamWriter sw;
op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
{
string t = textBox1.Text;
t = op.FileName;
FileInfo fi = new FileInfo(textBox1.Text = op.FileName);
n = fi.Name + "." + fi.Length;
client = new TcpClient("127.0.0.1", 8100);//"127.0.0.1", 5055
sw = new StreamWriter(client.GetStream());
s = client.GetStream();
b1 = File.ReadAllBytes(op.FileName);
// s = client.GetStream();
while (true)
{
s.Write(b1, 0, b1.Length);
sw.WriteLine(n);
sw.Flush();
//sw.Close();
s.Close();//added by me
Thread.Sleep(18000);
}
sw.Flush();
client.Close();
// label2.Text = "File Transferred....";
}
}
Server class:
public Form1()
{
InitializeComponent();
}
string rd;
byte[] b1;
string v;
int m=20;//number of byts
TcpListener list;
TcpClient client;
int port = 8100;//5050
int port1 = 8100;//5055
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
private void button1_Click(object sender, EventArgs e)//browse button
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
list = new TcpListener(localAddr, port1);
list.Start();
Thread incoming_connection = new Thread(ic);
incoming_connection.Start();
}
}
private void ic()
{
client = list.AcceptTcpClient();
Stream s = client.GetStream();
b1 = new byte[m];
s.Read(b1,0, b1.Length);
MessageBox.Show("pathh "+textBox1.Text);
File.WriteAllBytes(textBox1.Text+"\\flag.txt", b1);// the left side us the name of the written file
//list.Stop();
//client.Close();
// label1.Text = "File Received......";
}
private void Form2_Load(object sender, EventArgs e)
{
list = new TcpListener(localAddr, port);
// TcpListener list = new TcpListener(port);
list.Start();
TcpClient client = list.AcceptTcpClient();
MessageBox.Show("Client trying to connect");
StreamReader sr = new StreamReader(client.GetStream());
rd = sr.ReadLine();
v = rd.Substring(rd.LastIndexOf('.') + 1);
m = int.Parse(v);
// list.Stop();
// client.Close();
}