In one part of my application I send a file from one PC to another from a TCP socket, the connection and sending the file seems to me to be perfect, there are no problems since it is very simple, here the code:
IPEndPoint remoteEP = new IPEndPoint(ip, port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connectDone.Reset();
sendDone.Reset();
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
Controlador.PermitirEnviarArchivo.Set();
//Envio nombre del archivo
client.Send(Encoding.ASCII.GetBytes(Path.GetFileName(rutaArchivo) + "<KC>"));
//recivo el ok
client.Receive(new byte[1024]);
//envio el archivo
client.SendFile(rutaArchivo);
client.Shutdown(SocketShutdown.Send);
client.Close();
The problem I'm having when I receive it, I do not know if I'm using any index and offset wrong, I can not think of anything else to try! I show when I already established the connection
public void ReadCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
Configuracion c = new Configuracion().Leer();
if (!state.esArchivo)//Nombre del archivo
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
state.nombreArchivo += state.sb.ToString();
if (state.nombreArchivo.IndexOf("<KC>") > -1)
{
state.nombreArchivo = state.nombreArchivo.Split('<')[0];
handler.Send(Encoding.ASCII.GetBytes("<KC>"));
state.esArchivo = true;
if (File.Exists(c.rutaDescarga + "\" +state.nombreArchivo))
{
File.Delete(c.rutaDescarga + "\" + state.nombreArchivo);
}
state.buffer = new byte[StateObject.BufferSize];
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
else
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
else //Archivo
{
using (FileStream fs = new FileStream(c.rutaDescarga + "\" +state.nombreArchivo, FileMode.Append, FileAccess.Write))
{
fs.Write(state.buffer, 0, bytesRead);
}
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
}
}
and my StateObject object
public class StateObject
{
public string nombreArchivo = "";
public bool esArchivo = false;
public Socket workSocket = null;
public const int BufferSize = 1048576;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
error: I do not know what is happening, I gave up trying: c
Thank you!