Finally, the Post
method is used to add new articles to the forums. The post method takes four parameters; the newsgroup name, the subject, the sender and the body of the message.
public void Post(string newsgroup, string subject, string from,
string content)
{
string message;
string response;
message = "POST\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "340")
{
throw new NntpException(response);
}
message = "From: " + from + "\r\n"
+ "Newsgroups: " + newsgroup + "\r\n"
+ "Subject: " + subject + "\r\n\r\n"
+ content + "\r\n.\r\n";
Write(message);
response = Response();
if (response.Substring(0, 3) != "240")
{
throw new NntpException(response);
}
}
The Post method sends a POST
message to the NNTP server. The NNTP server should respond with a 340 status-code indicating that you may post. The headers and content of the post can then be sent to the server with a terminating single line containing one period. If the message is received correctly, the NNTP server will respond with a 240 status-code.
Our public methods used two private methods, Write
and Response
. The Write
method sends a string of bytes to the NNTP server.
private void Write(string message)
{
System.Text.ASCIIEncoding en = new System.Text.ASCIIEncoding() ;
byte[] WriteBuffer = new byte[1024] ;
WriteBuffer = en.GetBytes(message) ;
NetworkStream stream = GetStream() ;
stream.Write(WriteBuffer, 0, WriteBuffer.Length);
Debug.WriteLine(" WRITE:" + message);
}
It is important that we convert the .NET string to a series of bytes using ASCIIEncoding
before it is sent to the server. I also call the Debug.WriteLine
method to send the output string to the debug console to help with debugging this component. The second private method is the Response
method. The Response
method receives one line of input from the NNTP server.
private string Response()
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte [] serverbuff = new Byte[1024];
NetworkStream stream = GetStream();
int count = 0;
while (true)
{
byte [] buff = new Byte[2];
int bytes = stream.Read(buff, 0, 1 );
if (bytes == 1)
{
serverbuff[count] = buff[0];
count++;
if (buff[0] == '\n')
{
break;
}
}
else
{
break;
};
};
string retval = enc.GetString(serverbuff, 0, count );
Debug.WriteLine(" READ:" + retval);
return retval;
}
After receiving the single line of bytes, the data is translated into a .NET string from its ASCII encoded bytes.
Comments