a Little NNTP Example

This code provides NNTP server-client connection,
to join a group after that
to print the last article header of the group.


import org.apache.commons.net.nntp.*;
import java.io.*;
import java.util.*;
public class NNTPExample {

// the method parses the reply code that from nntp server
public static ArticlePointer getLastArticle(String replyString) {
StringTokenizer strToken = new StringTokenizer(replyString);
int status = Integer.parseInt(strToken.nextToken());
// the status 211 means group selected
if (status == 211) {
int articleCount = Integer.parseInt(strToken.nextToken());
int firstArticle = Integer.parseInt(strToken.nextToken());
int lastArticle = Integer.parseInt(strToken.nextToken());
String groupName = strToken.nextToken();
ArticlePointer ap = new ArticlePointer();
ap.articleNumber = lastArticle;
return ap;
}
return null;
}
// the method parses the article subject and converts to string
public static String getArticleSubject(Reader r) {
StringBuffer sb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(r);
String line = br.readLine();
while (line != null) {
if (line.indexOf("Subject:") != -1) {
return line.substring(line.indexOf(':') + 1);
}
line = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public static void main(String[] args) {
try {
NNTPClient client = new NNTPClient();

// server connection, 119 is default NNTP port number
client.connect("your_server_ip", 119);

// group selection
boolean status = client.selectNewsgroup("to_attend_group_name");
ArticlePointer ap = getLastArticle(client.getReplyString());
System.out.println(ap.articleNumber
+ ": "
+ getArticleSubject(client
.retrieveArticleHeader(ap.articleNumber)));

client.logout();
client.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}