Click here to Skip to main content
15,893,594 members
Articles / Programming Languages / C#
Article

Getting the list of groups in a news server

Rate me:
Please Sign up or sign in to vote.
3.75/5 (8 votes)
1 Jul 20032 min read 65K   172   27   10
Introduction to Socket programming

Introduction

This article will introduce you to socket programming in .NET via a practical application: getting all groups in a news server. To fully understand this article, you should have some knowledge about socket programming.

Using the code

To illustrate these things, we will make  a form which fetches all groups in a news server (e.g.. news.microsoft.com – the best and free news server I known) and put the results in a rich textbox.  Our form will connect to the server via TCP protocol and talking with it in NNTP protocol (you should reference RFC 977 at www.faqs.org to find more information about NNTP protocol. It’s rather simple). The following is the main source code

C#
private void clickGo(object sender, System.EventArgs ex)
{
  // Connect to server;
  TcpClient tcpClient = new TcpClient();          
  tcpClient.Connect("news.microsoft.com", 119);   
  NetworkStream networkStream = tcpClient.GetStream();
  StreamReader reader = new StreamReader(networkStream);
  StreamWriter writer = new StreamWriter(networkStream);
                  
  string s;
  reader.ReadLine(); // Server respones = "200 Server ready"
  writer.WriteLine("List");
  writer.Flush();
  s = reader.ReadLine();  // Server response = "215 Newsgroups follow"
  while (s != ".") // "." response means that the list comes to the end
  {
    s = reader.ReadLine();
    if (s != ".") 
    {
      s = s.Substring(0,s.IndexOf(' '));
      textList.Text = textList.Text+s+"\n";
    }
  }                       
  // Disconnect
  networkStream.Close();
  tcpClient.Close();
}

First, we connect to the server and open a new stream with these lines :-

C#
TcpClient tcpClient = new TcpClient(); 
tcpClient.Connect("news.microsoft.com", 119);
NetworkStream networkStream = tcpClient.GetStream();

networkStream is now purely a binary stream; so it is very difficult to use. We’ll turn it in to text-based stream with these lines of code:

C#
StreamReader reader = new StreamReader(networkStream);
StreamWriter writer = new StreamWriter(networkStream);

The remaining work is talking with the server in NNTP protocol to get the list of groups in a way which is no different from reading and writing in a console window. We can imagine that the server is a real person who is only able to talk in NNTP language.

C#
s1 = reader.ReadLine(); 
writer.WriteLine("List");
writer.Flush();
s2 = reader.ReadLine(); 

There is one thing that you should pay attention to : you must flush the buffer before reading from server. For example, when you order the server to send you the list of group

C#
writer.WriteLine("List"); // without flush

The command List is stored in the buffer, instead of being sent immediately to the server and , certainly, the server doesn’t receive the command "List". And when you read the answer from the server :-

C#
s2 = reader.ReadLine(); 

your application will hang because the server just waits and waits for your command. So, keep in your mind that you must call Flush before reading the answers from the server.

Final Notes

If you download the list via 56k Modem, it will take two or three minutes to complete. Be patient!  For keeping source-code simple , I assume that there is not any error when making the connection or enquiring the server. I’m not a native English speaker. So, I’m willing to receive your feed-back about the grammar and style of this article. Thanks.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Engineer
Vietnam Vietnam
My name is Ly Hoang Hai.
I am study at Ki Thuat TPHCM University in VietName (class MT00KSTN)
I’m proud to be a classmate with Mr Pham Thanh Phong, Mr Huynh Quang Thuan.

Comments and Discussions

 
GeneralGet the Messages Pin
kuerbis27-Sep-03 12:42
kuerbis27-Sep-03 12:42 
GeneralRe: Get the Messages Pin
Anonymous18-Oct-03 2:56
Anonymous18-Oct-03 2:56 
GeneralNetworkStream.Flush Method Pin
Jacob Slusser30-Jul-03 7:20
Jacob Slusser30-Jul-03 7:20 
GeneralRe: NetworkStream.Flush Method Pin
Markus Kraeutner21-Jan-05 11:32
sussMarkus Kraeutner21-Jan-05 11:32 
GeneralRe: NetworkStream.Flush Method Pin
Markus Kraeutner21-Jan-05 11:32
sussMarkus Kraeutner21-Jan-05 11:32 
GeneralRe: NetworkStream.Flush Method Pin
Jacob Slusser24-Jan-05 5:20
Jacob Slusser24-Jan-05 5:20 
QuestionWhere is my name and my portraits ? Pin
Ly Hoang Hai9-Jul-03 20:32
Ly Hoang Hai9-Jul-03 20:32 
AnswerRe: Where is my name and my portraits ? Pin
Nish Nishant9-Jul-03 21:42
sitebuilderNish Nishant9-Jul-03 21:42 
GeneralEasy but extreemly powerfull optimization Pin
Anders Dyhrberg8-Jul-03 11:21
professionalAnders Dyhrberg8-Jul-03 11:21 
Hi Member No. 457654 (Sorry but I could not find your name)

I looked at your nice little socket tutorial.
I find it nice and inspiering Smile | :) . This realy shows how easy it is to do great stuff in no time, using C#.

When I made the first run I thought my internet connection broke down, since it took me very long time (to long atleast) to retrieve the list.
Since I have 2Mbit down stream something had to be wrong, normally this only takes a few seconds.

So I took a look at your code and noticed the following:

while (s != ".") // the server send out "." to show that the list is end
{
	s = reader.ReadLine();
	if (s != ".") 
	{
		s = s.Substring(0,s.IndexOf(' '));
		textList.Text = textList.Text+s+"\n";
	}
}


This is the preformance killer: textList.Text = textList.Text+s+"\n";

Since this will make your computer work like crazy creating new string objects.
Remember the string is not overloaded to cascade extra strings using the + like in C++. Therefore this results in your computer creating a totally new string object and discarding the present one, everytime this line is run. In this case on time per group on microsoft newsserver.... hench MANY Smile | :) . and also leaving quite a bid og work for the Garbage Collecter. Dead | X|

Try changing the code to the following:

StringBuilder sb = new StringBuilder();
while (s != ".")
{
	 s = reader.ReadLine();
	 if (s != ".") 
	 {
		 s = s.Substring(0,s.IndexOf(' '));
		 sb.Append(s+"\n");
	 }
}

textList.Text = sb.ToString();

This is just one simple of many ways to fix it.

Just to make the sientific proof of my claims, I tried to add label to the form showing a measured execution time of each method. The inital method was 32.29 seconds to execute. The new easy improved method only used 2.14 seconds.

This Extreemly simpel change, made a factor 16 improvement on the code. Big Grin | :-D
Worth noticing is that this factor would keep grow exponentially, because the new string is always is created partially(almost totally) from the old sting data which is growing and growing and therefore more and more needs to be copied every iteration of the whileSleepy | :zzz:

I learned this the hard way myself when creating a cryto program where I needed to move around, large amounts of strings and chars alot.


Hope this comment was (or will be) worth your 5 minutes reading Smile | :)
Thanks

Anders Dyhrberg
GeneralRe: Easy but extreemly powerfull optimization Pin
Anonymous5-Jul-04 3:03
Anonymous5-Jul-04 3:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.