NNTP Protocol and C# 
Author Message
 NNTP Protocol and C#

Anyone have any sample code for accessing news group servers using NNTP?
I'm guessing I'd use the WebRequest base class, but it does not seem to like
the news URI prefix.
I'm interested in seeing any sample code for retrieving the news group lists
and then downloading messages from a given group.

TIA,

James Owens



Tue, 02 Mar 2004 09:52:10 GMT  
 NNTP Protocol and C#


Quote:
> Anyone have any sample code for accessing news group servers using NNTP?
> I'm guessing I'd use the WebRequest base class, but it does not seem to like
> the news URI prefix.
> I'm interested in seeing any sample code for retrieving the news group lists
> and then downloading messages from a given group.

Here's some VB.NET code that was thrown together back in Feb 2001 (using
Beta 1).  I massaged it a bit to compile under Beta 2.  It's not pretty,
but it gives you the gist of what to do.

(Beware of line breaks in the code below)

Imports System.Net.Sockets
Imports System.Text
Imports System.Collections.Specialized

Module Module1

    Sub Main()
        Dim oNews As NNTP = New NNTP("msnews.microsoft.com")
        Dim oGroups As StringCollection
        Dim sGrp As String
        Dim oMsg As NNTP.NNTP_Msg
        Dim oMsgs As NNTP.NNTP_Messages

        Console.WriteLine("Server Response:")
        Console.WriteLine("{0}", oNews.ConnectResponse)

        oGroups = oNews.Groups()
        Console.WriteLine("GROUPS")
        For Each sGrp In oGroups
            Console.WriteLine(sGrp)
        Next

        oNews.SelectGroup("microsoft.public.dotnet.faqs")

        'dim oMyList            as New StringCollection
        'with oMyList
        '       .Add("1")
        '       .Add("4")
        '       .Add("8")
        '       .Add("900")
        'end with
        'oMsgs = oNews.GetMessages(oMyList, True)
        'for each oMsg in oMsgs
        '       console.WriteLine("{1} - SUBJECT: {0}", oMsg.Headers
("subject"), oMsg.ID)
        'Next

        Console.WriteLine("HELP: {0}", oNews.SendCommand("HELP"))

        oNews.Dispose()
    End Sub

    Public Class NNTP
        Private ASCII As Encoding = Encoding.ASCII
        Private m_Split As RegularExpressions.Regex = New
RegularExpressions.Regex(Chr(13) & Chr(10))

        Private m_server As String    ' news server
        Private m_port As Integer     ' port
        Private m_socket As TcpClient   ' tcp socket
        Private m_connectResp As String = ""  ' connect response

        Private m_CurrGroup As String = ""   ' current selected group
        Private m_GroupCount As Integer   ' number of messages in grp
        Private m_FirstMsg As Integer    ' 1st message in group
        Private m_LastMsg As Integer    ' last message in group

        ' class that encapsulates an NNTP message

        Public Class NNTP_Msg
            Private m_headers As NameValueCollection ' collection of
headers
            Private m_id As String     ' message id
            Private m_body As String     ' body

            ' initialize variables
            Friend Sub New()
                m_headers = New NameValueCollection()
                m_id = ""
                m_body = ""
            End Sub

            Public ReadOnly Property Headers() As NameValueCollection
                Get
                    Return m_headers
                End Get
            End Property

            Public ReadOnly Property ID() As String
                Get
                    Return m_id
                End Get
            End Property

            Public ReadOnly Property Body() As String
                Get
                    Return m_body
                End Get
            End Property

            ' create one body string from the lines
            ' returned over the socket
            Friend Sub SetBody(ByVal sLines() As String)
                Dim sBody As String
                Dim i As Integer
                Dim sTmp As String

                sBody = ""
                For i = 1 To sLines.Length - 3
                    sBody = sBody & sLines(i) & Environment.NewLine
                Next
                m_body = sBody
            End Sub

            ' take the headers response, parse it and add
            ' it to the headers collection
            Friend Sub SetHeaders(ByVal sLines() As String)
                Dim i As Integer
                Dim sStat As String
                Dim sTmp As String

                sStat = sLines(0)
                sStat = Mid(sStat, sStat.IndexOf(" ") + 2)
                sStat = Mid(sStat, sStat.IndexOf(" ") + 2)
                sStat = Mid(sStat, sStat.IndexOf(" ") + 2)
                m_id = sStat

                For i = 1 To sLines.Length - 3
                    sTmp = sLines(i)
                    m_headers.Add(Left(sTmp, sTmp.IndexOf(":")), Mid
(sTmp, sTmp.IndexOf(":") + 3))
                Next
            End Sub

        End Class

        ' collection of nntp messages (for those commands that
        ' can return more than one message)
        Public Class NNTP_Messages
            Inherits System.Collections.ReadOnlyCollectionBase

            Public Sub New()
                MyBase.New()
            End Sub

            Public Sub Add(ByVal oMsg As NNTP_Msg)
                MyBase.InnerList.Add(oMsg)
            End Sub

        End Class

        Public ReadOnly Property ConnectResponse() As String
            Get
                Return m_connectResp
            End Get
        End Property

        ' constructor 1: server and port passed in
        Public Sub New(ByVal Server As String, ByVal Port As Integer)
            _New(Server, Port)
            m_connectResp = GetData()
        End Sub

        ' constructor 2: only server passed (port default to 119)
        Public Sub New(ByVal Server As String)
            _New(Server, 119)
            m_connectResp = GetData()
        End Sub

        ' actually open up the socket
        Private Sub _New(ByVal Server As String, ByVal Port As Integer)
            m_socket = New TcpClient(Server, Port)
            m_socket.ReceiveTimeout = 3
            m_server = Server
            m_port = Port
        End Sub

        ' disconnect and cleanup
        Public Sub Dispose()
            If Not m_socket Is Nothing Then
                Send("QUIT")
                GetData()
                m_socket.Close()
            End If
            m_socket = Nothing
        End Sub

        ' return a list of groups
        Public Function Groups() As StringCollection
            Dim sDump As String
            Dim sData As String
            Dim sList() As String
            Dim i As Integer
            Dim oColl As New StringCollection()

            Send("LIST")  ' send LIST command
            sDump = ""

            ' get the response
            sData = GetData()
            While sData <> ""
                sDump = sDump & sData
                sData = GetData()
            End While

            ' split it up and return it to caller
            sList = m_Split.Split(sDump)
            For i = 1 To sList.Length - 3
                oColl.Add(Left(sList(i), sList(i).IndexOf(" ")))
            Next i

            Return oColl
        End Function

        ' send a string of data over the socket
        Private Sub Send(ByVal sData As String)
            Dim bSend() As Byte = ASCII.GetBytes(sData &
Environment.NewLine)

            m_socket.GetStream.Write(bSend, 0, bSend.Length)
        End Sub

        ' get data from the socket
        Private Function GetData() As String
            Dim iBytes As Integer
            Dim bRecv(256) As Byte
            Dim sTmp As String

            Try
                iBytes = m_socket.GetStream.Read(bRecv, 0, bRecv.Length)
                sTmp = ASCII.GetString(bRecv, 0, iBytes)
            Catch e As Exception
                Return ""
            End Try

            While iBytes > 0
                Try
                    iBytes = m_socket.GetStream.Read(bRecv, 0,
bRecv.Length)
                    sTmp = sTmp & ASCII.GetString(bRecv, 0, iBytes)
                Catch e As Exception
                    Exit While
                End Try
            End While

            Return sTmp
        End Function

        ' select a particular group
        Public Sub SelectGroup(ByVal GroupName As String)
            Dim sData As String

            Send("GROUP " & GroupName)
            sData = GetData()
            ' check for errors
            If Left(sData, 3) = "411" Then
                Throw New Exception("No such group")
            End If
            m_CurrGroup = GroupName

            ' trim off result code
            sData = Mid(sData, sData.IndexOf(" ") + 2)
            m_GroupCount = Convert.ToInt32((Left(sData, sData.IndexOf("
"))))

            ' trim off result code
            sData = Mid(sData, sData.IndexOf(" ") + 2)
            m_FirstMsg = Convert.ToInt32(Left(sData, sData.IndexOf("
")))

            ' trim off result code
            sData = Mid(sData, sData.IndexOf(" ") + 2)
            m_LastMsg = Convert.ToInt32(Left(sData, sData.IndexOf(" ")))
        End Sub

        ' get an entire message
        Public Overloads Function GetMessage(ByVal param As String) As
NNTP_Msg
            Return _GetMessage(param, False)
        End Function

        ' get only a message header
        Public Overloads Function GetMessage(ByVal param As String,
ByVal OnlyHeader As Boolean) As NNTP_Msg
            Return _GetMessage(param, OnlyHeader)
        End Function

        ' retrieve a message from the server
        Private Function _GetMessage(ByVal param As String, ByVal
bOnlyHdr As Boolean) As NNTP_Msg
            Dim sData As String
            Dim oMsg As New NNTP_Msg()

            ' send HEAD command
            Send("HEAD " & param)
            sData = GetData()

            ' if no errors, continue
            If Left(sData, 1) = "2" Then
                ' parse out the headers
                oMsg.SetHeaders(m_Split.Split(sData))
                If Not bOnlyHdr Then
                    ' now ask for the body
                    Send("BODY " & param)
                    sData = GetData()
                    oMsg.SetBody(m_Split.Split(sData))
                End If
            End If

            Return oMsg
...

read more »



Tue, 02 Mar 2004 10:19:04 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. NNTP protocol: NetworkStream object buffer size

2. an nntp control or CSocket sample using nntp

3. C#-based NNTP server example?

4. Problem connecting to nntp server and sending commands

5. I just learned NNTP

6. nntp library ?

7. nntp sessions, TCP/IP

8. Help Needed in Reading Mails from POP3 and NNTP server

9. You just learned $#it (Re: I just learned NNTP)

10. I just learned NNTP

11. NEWTEST;SONDE;NNTP;255;Nntptest1;2003/3/18-18:15:22

12. public NNTP server for microsoft.public.vc.database ?

 

 
Powered by phpBB® Forum Software