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.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace EnvioArchivos
{
public partial class Form1 : Form
{
bool conectado = false;
Socket socket;
Thread trabajo;
public Form1()
{
InitializeComponent();
}
delegate void SetTextCallback(string text);
private void button1_Click(object sender, EventArgs e)
{
if (!conectado)
{
conectar();
conectado = true;
}
else
{
byte[] msn = System.Text.Encoding.ASCII.GetBytes("close");
socket.Send(msn);
desconectar();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
enviarArchivo(openFileDialog1.FileName);
}
}
private void conectar()
{
button1.Text = "Desconectar";
button2.Enabled = true;
button3.Enabled = true;
textBox3.Enabled = true;
IPAddress ipServer = Dns.GetHostEntry(textBox1.Text).AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipServer, 1050);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
addText("Intentando conectar...");
socket.Connect(ipEndPoint);
ParameterizedThreadStart threadMensajes = new ParameterizedThreadStart(this.checarMensajes);
trabajo = new Thread(threadMensajes);
trabajo.IsBackground = true;
trabajo.Start(socket);
if (socket.Connected)
{
addText("Conectado!!!");
}
}
catch (Exception e)
{
addText("Error al intentar conectar \r\n" + e.ToString());
button1.Text = "Conectar";
button2.Enabled = false;
conectado = false;
}
}
private void desconectar()
{
//trabajo.Join();
trabajo.Suspend();
socket.Close();
addText("Desconectado");
button1.Text = "Conectar";
button2.Enabled = false;
button3.Enabled = false;
textBox3.Enabled = false;
conectado = false;
}
private void enviarArchivo(string NombreFichero)
{
string RutaFichero = "";
NombreFichero = NombreFichero.Replace("\\", "/");
while (NombreFichero.IndexOf("/") > -1)
{
RutaFichero += NombreFichero.Substring(0, NombreFichero.IndexOf("/") + 1);
NombreFichero = NombreFichero.Substring(NombreFichero.IndexOf("/") + 1);
}
byte[] TamanoFicheroBytes = Encoding.ASCII.GetBytes(NombreFichero);
if (TamanoFicheroBytes.Length > 99999 * 2024)
{
addText("Tamaño del archivo es más de 200MB, por favor, pruebe con archivos pequeños.");
return;
}
//Msg = "Creando Cache buffer ...";
byte[] DatosFichero = File.ReadAllBytes(RutaFichero + NombreFichero);
byte[] TamanoFicheroEnviar = new byte[4 + TamanoFicheroBytes.Length + DatosFichero.Length];
addText("El peso a enviar " + TamanoFicheroBytes.Length.ToString() + " bytes");
addText("Enviando aviso de archivo y su peso");
byte[] byteAvisoArchivo = Encoding.ASCII.GetBytes("file:" + TamanoFicheroEnviar.Length.ToString());
socket.Send(byteAvisoArchivo);
byte[] fileNameLen = BitConverter.GetBytes(TamanoFicheroBytes.Length);
fileNameLen.CopyTo(TamanoFicheroEnviar, 0);
TamanoFicheroBytes.CopyTo(TamanoFicheroEnviar, 4);
DatosFichero.CopyTo(TamanoFicheroEnviar, 4 + TamanoFicheroBytes.Length);
addText("Enviando archivo...");
int bytesEnviados = socket.Send(TamanoFicheroEnviar);
addText("Se enviaron " + bytesEnviados.ToString() + " bytes");
addText("Enviando aviso que se termino de enviar el archivo");
byte[] byteAvisoEndArchivo = Encoding.ASCII.GetBytes("endfile");
//socket.Send(byteAvisoEndArchivo);
}
private void addText(string texto)
{
if (textBox2.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(addText);
this.Invoke(d, new object[] { texto });
}
else
{
string datetime = DateTime.Now.ToString();
string[] partes = datetime.Split(' ');
string hora = partes[1] + " " + partes[2];
if (textBox2.Text == "")
{
textBox2.Text = hora + " " + texto;
}
else
{
textBox2.Text = hora + " " + texto + "\r\n" + textBox2.Text;
}
}
}
private void button3_Click(object sender, EventArgs e)
{
if (socket.Connected)
{
enviarTexto(textBox3.Text);
if (textBox3.Text == "close")
{
desconectar();
}
textBox3.Text = "";
}
}
private void enviarTexto(string texto) {
if (this.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(enviarTexto);
this.Invoke(d, new object[] { texto });
}
else
{
byte[] msn = System.Text.Encoding.ASCII.GetBytes(texto);
socket.Send(msn);
}
}
private void checarMensajes(object orSocket)
{
//bool conectado = true;
int numPasadas = 1;
Socket socket = (Socket) orSocket;
addText("Iniciando escucha");
while (true)
{
if (socket.Connected)
{
byte[] bytesRecibidos = new byte[1024];
int info = socket.Receive(bytesRecibidos);
string texto = System.Text.Encoding.ASCII.GetString(bytesRecibidos, 0, info);
if (texto == "recibido")
{
addText("Se recibio mensaje del servidor");
enviarTexto("endfile");
}
numPasadas++;
}
checarMensajesNum(numPasadas.ToString());
}
}
private void checarMensajesNum(string num)
{
if (this.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(checarMensajesNum);
this.Invoke(d, new object[] { num });
}
else
{
textBox4.Text = num;
}
}
}
}