Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Developing an NNTP Newsgroup Reader

Learn how to develop a C# application that retrieves the available newsgroups from an NNTP server and then displays the articles from those specific newsgroups.

On Sunday, July 29th 2007 at 01:11 AM
By Andrew Pociu (View Profile)
*****   (Rated 4.8 with 5 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (Visual Studio 2005)

Latest technology meets 1986 ARPA-Internet
In this tutorial we're going to develop an application that communicates through a transfer protocol developed over 20 years ago but that is still commonly used to this day. NNTP is the Network News Transfer Protocol that's responsible for all those Usenet articles but also the protocol used by news.microsoft.com - a large message board for developers and other IT professionals using Microsoft technologies. But let's move on to coding the actual thing.

Start Visual Studio 2005 and create a new C# Windows Application. Add four TextBoxes to it, a ComboBox, and three Buttons: txtNNTPServer, txtLog, txtHead, txtBody, cmbNewsgroups, btnGo, btnGetNews and finally btnNextArticle. Except for txtNNTPServer, the other three TextBoxes should have the Multiline property set to True . Arrange your form to look similar to this one below:

NNTP Reader Form

Now we can do some coding. A using statement for the System.Net.Sockets namespace is the first thing:


using System.Net.Sockets;


Now inside the class we're going to create some of the objects that we're going to use:


// Used for receiving info

byte[] downBuffer = new byte[2048];

// Used for sending commands

byte[] byteSendInfo = new byte[2048];

// Used for connecting a socket to the NNTP server

TcpClient tcpClient;

// Used for sending and receiving information

NetworkStream strRemote;

// Stores various responses

string Response;

// Number of bytes in the buffer

int bytesSize;

// Stores the ID of the first message in a newsgroup

int firstID;

// Stores the ID of the last message in a newsgroup

int lastID;

// Stores chunks of the articles from the buffer

string NewChunk;


We're planning to send written commands to the NNTP server, but the NNTP server expects a stream of bytes. Thus, in order to send commands to the server we need to create a simple method that will handle this conversion:


public static byte[] StringToByteArr(string str)

{

    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

    return encoding.GetBytes(str);

}


The first real action that the application takes is when the btnGo button gets clicked. The following piece of code will connect to the actual NNTP server specified in the txtNNTPServer TextBox. It then sends a LIST command to the server, which in returns responds with a list of the newsgroups available. The list of newsgroups however needs to be looped line by line before it can be used, so that we can put the appropriate values in the ComboBox.


private void btnGo_Click(object sender, EventArgs e)

{

    // Open the socket to the server

    tcpClient = new System.Net.Sockets.TcpClient(txtNNTPServer.Text, 119);

    strRemote = tcpClient.GetStream();

    // Read the bytes

    bytesSize = strRemote.Read(downBuffer, 0, 2048);

    // Retrieve the response

    Response = System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize);

    // Just as in HTTP, if code 200 is not returned, something's not right

    if (Response.Substring(0, 3) != "200")

    {

        MessageBox.Show("The server returned an unexpected response.", "Connection failed", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    // Show the response

    txtLog.Text = Response + "\n";

 

    // Make the request to list all newsgroups

    byteSendInfo = StringToByteArr("LIST\r\n");

    strRemote.Write(byteSendInfo, 0, byteSendInfo.Length);

    Response = "";

 

    // Loop to retrieve a list of newsgroups

    while ((bytesSize = strRemote.Read(downBuffer, 0, downBuffer.Length)) > 0)

    {

        // Get the chunk of string

        NewChunk = Encoding.ASCII.GetString(downBuffer, 0, bytesSize);

        Response += NewChunk;

        // If the string ends in a "\r\n.\r\n" then the list is over

        if (NewChunk.Substring(NewChunk.Length - 5, 5) == "\r\n.\r\n")

        {

            // Remove the "\r\n.\r\n" from the end of the string

            Response = Response.Substring(0, Response.Length - 3);

            break;

        }

    }

    // Split lines into an array

    string[] ListLines = Response.Split('\n');

    // Loop line by line

    foreach (String ListLine in ListLines)

    {

        // If the response starts with 215, it's the line that indicates the status

        if (ListLine.Length > 3 && ListLine.Substring(0, 3) == "215")

        {

            // Add the status response line to the log window

            txtLog.Text += ListLine + "\r\n";

        }

        else

        {

            // Add the newsgroup to the combobox

            string[] Newsgroup = ListLine.Split(' ');

            cmbNewsgroups.Items.Add(Newsgroup[0]);

        }

    }

}


At this point we're done with the code that retrieves the newsgroups. The next button that should be clicked is btnGetNews which - using the GROUP command followed by the ID of the desired newsgroup - will retrieve certain information about that newsgroup, more importantly the ID of the first article and of the last article. This will help us get the actual articles of that newsgroup, since we're going to retrieve them by ID.


private void btnGetNews_Click(object sender, EventArgs e)

{

    // If a newsgroup is selected in the ComboBox

    if (cmbNewsgroups.SelectedIndex != -1)

    {

        // Request a certain newsgroup

        byteSendInfo = StringToByteArr("GROUP " + cmbNewsgroups.SelectedItem.ToString() + "\r\n");

        strRemote.Write(byteSendInfo, 0, byteSendInfo.Length);

        Response = "";

        bytesSize = strRemote.Read(downBuffer, 0, 2048);

        Response = System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize);

        // Split the information about the newsgroup by blank spaces

        string[] Group = System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize).Split(' ');

        // Show information about the newsgroup in the txtLog TextBox

        Response += Group[1] + " messages in the group (messages " + Group[2] + " through " + Group[3] + ")\r\n";

        txtLog.Text += Response;

        Response = "";

        // The ID of the first article in this newsgroup

        firstID = Convert.ToInt32(Group[2]);

        // The ID of the last article in this newsgroup

        lastID = Convert.ToInt32(Group[3]);

    }

    else

    {

        MessageBox.Show("Please connect to a server and select a newsgroup from the dropdown list first.", "Newsgroup retrieval", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}


Believe it or not, all that's left is the actual retrieveal of the message/article. The ARTICLE command sounds like the straightforward solution to this, however that will return the header and body of the message into a single piece of string, and most of the time you'll want to retrieve these two separately. This can be easily done by sending the HEAD and BODY commands, each followed by the ID of the article you wish to retrieve. We start with the latest message moving on to the older ones with each click of btnNext:


private void btnNext_Click(object sender, EventArgs e)

{

    if (tcpClient != null && tcpClient.Connected == true && firstID >= 0)

    {

        // Get the header

        txtHead.Text = "";

        // Initialize the buffer to 2048 bytes

        downBuffer = new byte[2048];

        // Request the headers of the article

        byteSendInfo = StringToByteArr("HEAD " + firstID + "\r\n");

        // Send the request to the NNTP server

        strRemote.Write(byteSendInfo, 0, byteSendInfo.Length);

        while ((bytesSize = strRemote.Read(downBuffer, 0, downBuffer.Length)) > 0)

        {

            NewChunk = System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize);

            txtHead.Text += NewChunk;

            // If the last thing in the buffer is "\r\n.\r\n" the message's finished

            if (NewChunk.Substring(NewChunk.Length - 5, 5) == "\r\n.\r\n")

            {

                break;

            }

        }

 

        // Get the body

        txtBody.Text = "";

        // Initialize the buffer to 2048 bytes

        downBuffer = new byte[2048];

        // Request the headers of the article

        byteSendInfo = StringToByteArr("BODY " + firstID + "\r\n");

        // Send the request to the NNTP server

        strRemote.Write(byteSendInfo, 0, byteSendInfo.Length);

        while ((bytesSize = strRemote.Read(downBuffer, 0, downBuffer.Length)) > 0)

        {

            NewChunk = System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize);

            txtBody.Text += NewChunk;

            // If the last thing in the buffer is "\r\n.\r\n" the message's finished

            if (NewChunk.Substring(NewChunk.Length - 5, 5) == "\r\n.\r\n")

            {

                break;

            }

        }

 

        // Ready for the next article, unless there is nothing else there...

        if (firstID <= lastID)

        {

            firstID++;

        }

    }

    else

    {

        MessageBox.Show("Please select a newsgroup from the dropdown list and click on 'Get News' first.", "Newsgroup retrieval", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}



Well, that's all there is to retrieving the newsgroups and messages from an NNTP server. From this point on to creating a full blown NNTP reader there is plenty of parsing to be done in the headers so as to arrange the messages in a meaningful manner. Also another command that's not covered in this tutorial because it's simple enough to integrate is POST which allows the posting of a message in a newsgroup, as a new subject or as a reply to existing messages.

To get more information on NNTP, read the protocol's reference dated February 1986: http://www.ietf.org/rfc/rfc977.txt

And here's our little application in action:

NNTP Reader Application
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Andrei Pociu on Friday, August 31st 2007 at 10:57 PM

I replaced the project file with an updated version that fixes a problem where if an article is not available for retrieval when clicking on "Next Article", it now moves to the next article, instead of getting stuck in a while loop and eventually crashing.

by amit verma on Wednesday, June 18th 2008 at 11:37 AM

hey im getting following error when click on go button "No connection could be made because the target machine actively refused it" any idea?

by Paul on Friday, May 1st 2009 at 01:45 AM

My nntp server requires authentication. How do I supply credentials to the server?

by PatteDePoule on Wednesday, October 14th 2009 at 11:39 AM

@Paul

http://www.cfmfrance.com/rfc.aspx?rfc=2980

by heart attack on Saturday, August 13th 2011 at 06:52 AM

I conceptualize this is a distinct put. Thanks for attractive the trim to score specific an exemplifying article. It has assumption me a lot of inspiration.

by love story on Monday, August 15th 2011 at 05:55 AM

Dig folks, I connexion you should cerebrate various dynamical a equal grouping, am I nonprogressive? Or at lesser colourise the comments. Anyways I sought to say that I likable this exclude on Facebook.

by Testking 70-649 on Monday, September 19th 2011 at 07:22 AM

Your postlooks great! I enjoyed.Thanks you for sharing. I love it.

by HappyChap on Friday, October 14th 2011 at 07:58 AM

This gave me a great start to creating an app that works the way I WANT it to work

Thanks for sharing :)

by happy new year sms on Monday, November 14th 2011 at 09:34 AM

This site is like no reason, very rich in content, choice of materials is very nice, too fond of, and a collection of sms.

by apply for credit cards on Monday, December 12th 2011 at 05:14 AM

i need more explanation on remember me checkbox using cookies and Wonderful! I am such a big fan of the blue ridge mountains. There is nothing better then this beauty.and also i want to known that how to assign cookies in one page and get cookies from Another page, but those things r done only in JAVASCRIPT.. [ASP.NET] Help Me...

by Phen375 on Monday, December 19th 2011 at 06:01 PM

Your personal know-how and kindness in maneuvering every part was tremendous. I am not sure what I would've done if I hadn't encountered such a solution like this. I'm able to at this time look ahead to my future. Thanks a lot so much for the specialized and result oriented help. I won't hesitate to endorse the blog to anybody who desires assistance on this topic.

by GenF20 Plus on Monday, December 19th 2011 at 06:02 PM

Your personal know-how and kindness in maneuvering every part was tremendous. I am not sure what I would've done if I hadn't encountered such a solution like this. I'm able to at this time look ahead to my future. Thanks a lot so much for the specialized and result oriented help. I won't hesitate to endorse the blog to anybody who desires assistance on this topic.

by GenFX on Monday, December 19th 2011 at 06:03 PM

Your personal know-how and kindness in maneuvering every part was tremendous. I am not sure what I would've done if I hadn't encountered such a solution like this. I'm able to at this time look ahead to my future. Thanks a lot so much for the specialized and result oriented help. I won't hesitate to endorse the blog to anybody who desires assistance on this topic.

by Teeth Whitening Reviews on Tuesday, December 20th 2011 at 01:39 AM

I truly wanted to write a quick message to thank you for some of the splendid points you are showing at this website. My long internet investigation has at the end been compensated with sensible facts and techniques to share with my family and friends.

by Human Growth Hormone on Tuesday, December 20th 2011 at 01:41 AM

I truly wanted to write a quick message to thank you for some of the splendid points you are showing at this website. My long internet investigation has at the end been compensated with sensible facts and techniques to share with my family and friends.

by Best Diet Pills on Tuesday, December 20th 2011 at 01:46 AM

I would believe that we visitors are truly blessed to dwell in a wonderful network with many wonderful professionals with very beneficial hints. I feel extremely privileged to have seen the web pages and look forward to many more pleasurable times reading here. Thank you once again for everything.

by HGH Advanced on Tuesday, December 20th 2011 at 01:53 AM

I would believe that we visitors are truly blessed to dwell in a wonderful network with many wonderful professionals with very beneficial hints. I feel extremely privileged to have seen the web pages and look forward to many more pleasurable times reading here. Thank you once again for everything.

by Dental White on Tuesday, December 20th 2011 at 01:56 AM


Thanks so much for providing individuals with an extremely remarkable possiblity to read critical reviews from this web site. It is always so beneficial plus jam-packed with a great time for me personally and my office friends to search the blog at the least three times in one week to see the fresh secrets you will have.

by Pure Acai Berry Max on Tuesday, December 20th 2011 at 01:59 AM


Thanks so much for providing individuals with an extremely remarkable possiblity to read critical reviews from this web site. It is always so beneficial plus jam-packed with a great time for me personally and my office friends to search the blog at the least three times in one week to see the fresh secrets you will have.

by Ultimate Maqui Berry on Tuesday, December 20th 2011 at 02:02 AM

I am just always happy with your good tips and hints served by you. Some 1 areas in this article are undeniably the finest I've had.

by Proactol Plus on Tuesday, December 20th 2011 at 02:04 AM

I am just always happy with your good tips and hints served by you. Some 1 areas in this article are undeniably the finest I've had.

by Provacyl on Tuesday, December 20th 2011 at 02:09 AM

I am just always happy with your good tips and hints served by you. Some 1 areas in this article are undeniably the finest I've had.

by Nuratrim on Tuesday, December 20th 2011 at 02:13 AM

Thanks a lot for providing individuals with remarkably special possiblity to read critical reviews from this web site. It can be very kind plus packed with a great time for me personally and my office mates to visit your site no less than three times weekly to study the newest tips you have.

by Capsiplex on Tuesday, December 20th 2011 at 02:20 AM

Thanks a lot for providing individuals with remarkably special possiblity to read critical reviews from this web site. It can be very kind plus packed with a great time for me personally and my office mates to visit your site no less than three times weekly to study the newest tips you have.

by DoraHampton34 on Thursday, December 22nd 2011 at 10:07 AM

Some time before, I did need to buy a car for my business but I didn't earn enough money and couldn't order something. Thank goodness my colleague suggested to take the loans at trustworthy bank. Thus, I did so and was happy with my sba loan.

by on Saturday, January 14th 2012 at 01:20 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by mensagens de aniversario on Saturday, January 21st 2012 at 02:58 AM

As previous posters have said, this information (along with resources like the Wises Directories) are absolutely crucial and critical in family research!

by mensagens de amizade on Saturday, January 21st 2012 at 03:01 AM

As previous posters have said, this information (along with resources like the Wises Directories) are absolutely crucial and critical in family research!

by jogos da barbie on Saturday, January 21st 2012 at 04:08 AM

I accept never approved it, but I would anticipate that it should plan in Haiku. Give it a shot.

The app is commercial, but the columnist is not developing it anymore and has appear a key so that the affairs never expires. You can get it here:

by gdpoker on Saturday, January 21st 2012 at 06:49 PM

Excellent read, I just passed this onto a colleague who was doing some research on that. And he just bought me lunch since I found it for him smile Therefore let me rephrase that: Thank you for lunch!

by re on Thursday, February 9th 2012 at 01:33 PM

I appreciate the information and will look forward to future updates.
Thank you.
professional essay writers|
personal statement ucas

by Write my essay for me on Thursday, February 9th 2012 at 01:37 PM

I am determining to wee your towering way of connector the playacting. Now you danger it macerate for me to maturate and get the theory. Add you for the airman.Write my essay for me

by professional essay writers on Thursday, February 9th 2012 at 02:21 PM

I appreciate the information and will look forward to future updates.
Thank you.

by personal statement ucas on Thursday, February 9th 2012 at 02:22 PM

I appreciate the information and will look forward to future updates.

by wedding ring sets on Monday, February 13th 2012 at 09:06 AM

I conceptualize this is a distinct put. Thanks for attractive the trim to score specific an exemplifying article. It has assumption me a lot of inspiration....Thanks

by wedding rings sets on Monday, February 13th 2012 at 09:08 AM

I conceptualize this is a distinct put. Thanks for attractive the trim to score specific an exemplifying article. It has assumption me a lot of inspiration....Thanks

by wedding rings sets on Monday, February 13th 2012 at 09:09 AM

I am just always happy with your good tips and hints served by you. Some 1 areas in this article are undeniably the finest I've had.....Thanks

by wedding rings sets on Monday, February 13th 2012 at 09:09 AM

I am just always happy with your good tips and hints served by you. Some 1 areas in this article are undeniably the finest I've had.....Thanks

by re on Monday, February 13th 2012 at 01:00 PM

I conceptualize this is a distinct put. Thanks for attractive the trim to score specific an exemplifying article.

Write my essay | services review

by המשיח on Tuesday, February 14th 2012 at 09:35 AM

Thank you for another essential article. Where else could anyone get that kind of information in such a complete way of writing? I have a presentation incoming week, and I was on the lookout for such information...thank

by Mensagens Para Orkut on Thursday, February 23rd 2012 at 02:43 AM

Thanks a lot for providing individuals with remarkably special possiblity to read critical reviews from this web site. It can be very kind plus packed with a great time for me personally and my office mates to visit your site no less than three times weekly to study the newest tips you have...thanks

by beats by dre on Wednesday, March 14th 2012 at 03:57 AM

Votre écriture-up est très bon, l'étude de votre article, permettez-moi avantagerbeaucoup, je crois que je vais voulons absolument superbe étude de votre article.

by jhon on Friday, June 1st 2012 at 12:24 PM

nice tutorial it is so helpful thanks for sharing.
regards
http://www.quoteofthedaycollection.com

by Bob on Thursday, June 21st 2012 at 05:02 AM

Spam fail

by Fred on Thursday, June 21st 2012 at 05:05 AM

Too much spam here!

by WAI on Monday, July 2nd 2012 at 12:04 AM

This tutorial help me a lot on my term assignment!

Thanks!
Thanks!

by retrosleuth.com on Tuesday, September 25th 2012 at 09:57 AM

I don't think it's good to use cell phone saerches.

by on Thursday, November 1st 2012 at 05:35 AM

I was on the lookout for such information...thank


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources