using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
namespace FileTransfer
{
public partial class Form1 : Form
{
private Thread connector;
private TcpClient client;
private volatile NetworkStream stream;
private IPAddress ip;
private volatile bool connectorRunning;
private readonly int port = 21341;
private readonly int STREAM_PREFIX = -2;
private string fileToSend;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SetStatus(false);
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (connectorRunning)
{
log("O conector já esta em uso!.");
return;
}
try
{
ip = IPAddress.Parse(txtIP.Text);
}
catch (Exception ee)
{
log(ee.Message);
}
connectorRunning = true;
connector = new Thread(startConnection);
connector.Name = "Conector";
//connector.IsBackground = true;
connector.Start();
}
private void SetStatus(bool connected)
{
MethodInvoker mi = delegate()
{
btnSend.Enabled = connected;
btnConnect.Enabled = !connected;
lblStatus.Text = connected ? "Conectado" : "Disconectado";
};
this.BeginInvoke(mi);
}
private void log(string msg)
{
MethodInvoker mi = delegate()
{
txtLogs.AppendText(msg);
txtLogs.AppendText("\r\n");
txtLogs.SelectionStart = txtLogs.Text.Length;
txtLogs.ScrollToCaret();
};
if (this.InvokeRequired)
this.BeginInvoke(mi);
else
mi.Invoke();
}
private void startConnection()
{
try
{
client = new TcpClient();
client.Connect(ip, port);
log("Connected!");
SetStatus(true);
stream = client.GetStream();
BinaryReader br = new BinaryReader(stream);
string fileName = "";
while (connectorRunning)
{
string prefix = br.ReadString();
if(prefix.Length > 0)
{
log(string.Format("Prefixo recebido >> {0} - {1}", prefix, prefix.Length));
if (prefix == "SFF") //regular message
{
while((fileName = br.ReadString()).Length == 0 && fileName.Replace(" ", "").Length == 0);
log("Receiving: " + fileName);
fileName = System.IO.Path.Combine(Environment.CurrentDirectory, fileName);
}
else if (prefix == "SFD") //stream message
{
string SizeStr;
while((SizeStr = br.ReadString()).Length == 0 && SizeStr.Replace(" ", "").Length == 0);
int Size = int.Parse(SizeStr);
log(string.Format("Tamanho recebido: {0}", Size));
long length = br.ReadInt64(); //total stream length
log(string.Format("Inicializando download ({0})..", length));
Adler32 adler = new Adler32();
// using (FileStream fs = new FileStream(fileName, FileMode.Create)) //isso n tem a ver? n
if(File.Exists(fileName))
File.Delete(fileName);
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
{
log(string.Format("Recebendo arquivo \"{0}\"!", fileName));
int total = 0;
int received = 0;
byte[] buffer = new byte[Size - total < 1024 ? Size - total : 1024];
while ((total += (received = stream.Read(buffer, 0, buffer.Length))) < Size)
{
this.Text = string.Format("Total: {0} - {1} => {2}", total, received, buffer.Length);
fs.Write(buffer, 0, received);
adler.Update(buffer, 0, received);
}
log("Fim!");
}
long checkSum = br.ReadInt64();
log(string.Format("Verifique o sol: {0} => {1}", checkSum, adler.Value));
if (checkSum != adler.Value)
{
throw new Exception("Checksum does not match.");
}
log("File received successfully.");
}
else
{
throw new Exception("Unexpected value: " + prefix);
}
}
}
log("End of the connection");
}
catch (Exception e)
{
log(e.Message);
log(e.StackTrace);
SetStatus(false);
connectorRunning = false;
}
}
protected override void OnClosing(CancelEventArgs e)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
private void btnSend_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
btnSend.Enabled = false;
fileToSend = openFileDialog1.FileName;
Thread sendThread = new Thread(sendFile);
sendThread.Name = "SendThread";
sendThread.IsBackground = true;
sendThread.Start();
}
}
private void sendFile()
{
try
{
Adler32 adler = new Adler32();
log("Sending: " + fileToSend);
using (FileStream fs = new FileStream(fileToSend, FileMode.Open))
{
byte[] name = Encoding.UTF8.GetBytes(Path.GetFileName(fileToSend));
BinaryWriter bw = new BinaryWriter(stream);
//send the first message which is the file name
bw.Write(name.Length);
bw.Write(name);
//send the stream message
bw.Write(STREAM_PREFIX);
long size = new FileInfo(fileToSend).Length;
bw.Write(size);
long written = 0;
byte[] buffer = new byte[8192];
while (written < size)
{
int count = fs.Read(buffer, 0, Math.Min((int)(size - written), buffer.Length));
stream.Write(buffer, 0, count);
adler.Update(buffer, 0, count);
written += count;
}
bw.Write(adler.Value);
log("File sent successfully.");
}
}
catch (Exception e)
{
log(e.Message);
}
MethodInvoker mi = delegate()
{
btnSend.Enabled = !btnConnect.Enabled;
};
this.BeginInvoke(mi);
}
}
}