Ho dato uno sguardo veloce al codice sembra ok, solo nel metodo ReadCallback c'è questa parte di codice può farti quel difetto, che in realtà non è un difetto, è una cosa voluta;
codice:
if (content.IndexOf("<EOF>") > -1) {
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content );
// Echo the data back to the client.
Send(handler, content);
} else {
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
praticamente questa parte di codice fa questo:
se la stringa letta contiente un End of File stampa nella console il numero di byte letti e la stringa letta e la reinvia al Client quando il trasferimento al client è terminato viene richiamato un altro metodo che si chiama SendCallBack (andremo a vederlo dopo).
Invece se la stringa non contiente l'eof continua a ricevere dei dati.
il metodo Send CallBack:
codice:
private static void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket handler = (Socket) ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
qui il probema, invece di rimettere di ascoltare ancora il socket con un handler.BeginReceive(...), chiude la connessione del socket e non ricevi + niente.
soluzioni:
se il cliente invia un eof per ogni trasmissione allora puoi lasciare quella condizione altrimenti la elimini. Cmq se vuoi restare in Streaming il metodo beginReceive lo devi chiamare sempre:
Eliminiamo il blocco else
codice:
if (content.IndexOf("<EOF>") > -1) {
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content );
// Echo the data back to the client.
Send(handler, content);
}
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
poi elimina la chiusura del socket dal blocco sendCallback
codice:
private static void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket handler = (Socket) ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
così dovrebbe andare...ovviamente non l'ho provato!