I am trying to develop a simple telnet client in MS.NET
I have a small wrapper around the System.Net.Sockets.Socket class
which takes care of sending and receiving data and handing it off to a
protocol handler.
What I am finding is that if I set my receive buffer size to 1 byte
this code will 'lose' characters, yet when I set the buffer to more
than 1 byte all works fine.
The problem is, that since it seems that most telnet clients operate
in 'byte at a time' mode I really want the single byte buffer
processing to work.
Has anyone else experienced a problem similar to this, and if so, what
do you do to fix it ?
private static void ReceiveCallback(IAsyncResult ar)
{
System.Threading.Monitor.Enter(recvCS);
// Retrieve the psuedo this object.
Connection psuedoThis = (Connection) ar.AsyncState;
// and get stuff we need to do our work
Socket theSocket = psuedoThis.workSocket_;
if(!ReallyConnected(theSocket)) // seems to be a problem with
detecting disconnects
{
System.Environment.Exit(-1);
}
// Read data from the client socket
int bytesRead = theSocket.EndReceive(ar);
String trace = "Socket[" + theSocket.Handle.ToString() + "] read " +
bytesRead.ToString() + " bytes from " +
theSocket.RemoteEndPoint.ToString();
System.Diagnostics.Debug.WriteLine(trace);
// take a copy of the inbound data
byte[] copy = new byte[bytesRead];
for(int i = 0; i < bytesRead; i++)
copy[i] = psuedoThis.buffer_[i];
// hand it off the the protocol handler
foreach(byte b in copy)
{
byte[] reply = psuedoThis.protocol_.handleMsg(b);
// if the protocol handler returns a reply, this must be sent NOW !
if(reply != null)
{
psuedoThis.Send(reply);
System.Console.WriteLine("Sending Reply {0}",
psuedoThis.protocol_.humanReadable(reply));
psuedoThis.Wait();
System.Console.WriteLine("Sending completed");
}
}
// resume asynchronous operation on the socket
psuedoThis.shutdownResult_ = theSocket.BeginReceive(
psuedoThis.buffer_,
0,
BufferSize,
SocketFlags.None,
psuedoThis.asyncCallback(CBType.Receive),
psuedoThis );
System.Threading.Monitor.Exit(recvCS);
}