new to socket programming; did i miss anything?

D

Dan Holmes

Would someone be kind enough to read this code and offer opinions about it? This code is in a service if that matters.

protected override void OnStart(string[] args)
{
try
{
eventLog1.Log = "Application";
eventLog1.Source = "RSEService";
int port = Properties.Settings.Default.Port;
listener = new SNS.TcpListener(port);
listener.Start();
listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener);
}
catch (Exception ex)
{

}
}
private void DoAcceptTcpClientCallback(IAsyncResult ar)
{
try
{
SNS.TcpListener listener = (SNS.TcpListener)ar.AsyncState;
SNS.TcpClient clientSckt = listener.EndAcceptTcpClient(ar);
listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener);
byte[] readbuffer = new byte[Initial_Buffer_Size];
SNS.NetworkStream ns = clientSckt.GetStream();
StringBuilder message = new StringBuilder();
while (true)
{
int bytesread = ns.Read(readbuffer, 0, readbuffer.Length);
if (bytesread == 0) break;
message.Append( Encoding.UTF8.GetString(readbuffer, 0, bytesread-1));
}
if (message.Length > 0)
{
string answer = ProcessQuestion(message.ToString());

if (ns.CanWrite)
{
byte[] writebuffer = Encoding.UTF8.GetBytes(answer);
ns.Write(writebuffer, 0, writebuffer.Length);
}
else
eventLog1.WriteEntry("Couldn't write");
}
clientSckt.Client.Disconnect(true);
clientSckt.Close();

}
catch (Exception ex)
{
eventLog1.WriteEntry(ex.ToString(), EventLogEntryType.Error);
}
}
 
D

Dan Holmes

Peter said:
Three comments:

-- You didn't post a concise-but-complete code sample, so we have no
idea what "SNS" is here. One hopes it's just an alias for the
System.Net.Sockets namespace, but there's no way to know.
that was a correct guess.
-- You should not tie up your accept callback with the entire client
processing. These callbacks should involve only the minimal processing,
so that you don't keep an IOCP thread pool thread from being available
for processing future i/o completions. In this case, you should
continue using async i/o for the socket reads (e.g.
Socket.BeginReceive() or Stream.BeginRead()), and then have a separate
thread for dealing with the server response (at the minimum, queue that
work on the regular ThreadPool, assuming you don't want to manage the
threading yourself).

Do you know of an example of this already on the web somewhere? I looked and couldn't find one. The BeginRead i
understand it is integrating that with the thread pool that i don't.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top