Named Pipe Input Output in C# - c#

I am working with named pipes and very confused about how the interaction between the client and server is happening.
My server is a VM with a named pipe attached to it. I have created a client stream in C# this way:
NamedPipeClientStream client = new NamedPipeClientStream(".", "TestPipe", PipeDirection.InOut);
Let's say the VM prompt is like below:
Hello!
Do you accept (y/n): y
Text1 : 1.2.3.4
Text2 : 2.3.4.5
What I essentially need to do is, check if the line read by the stream is "Do you accept (y/n):", if it matches then write y to the stream.es with Text1, then write 1.2.3.4 in the stream
Problems I am facing:
The prompt doesn't display anything after Hello!. What I thought
is, it is maybe waiting for the next input. So, instead of doing
this:
if(line.contains("Do you accept (y/n):"))
writer.writeLine("y")
I did this:
if(line.contains("Hello!"))
writer.writeLine("y");
Is this the correct thing? If it is, then it means that the server
isn't pushing the text in the buffer on which it is awaiting input.
So, every time I'll have to do the check for the previous line and
write the output of the next expected line to the writer stream?
Also, as per above, for passing 1.2.3.4 for Text1, I did this:
if(line.contains("Do you accept (y/n):"))
writer.writeLine("1.2.3.4")
What appears in my execution prompt is: Text1 : 1111111 ie. it's
only repeating the first character of the input I have passed. Why
such? I have already set AutoFlush = true to my writer stream.
Any pointers here will be highly appreciated!
Edit: Including the snippet
using System;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Windows;
namespace App1 {
static void Main(string [] args) {
NamedPipeClientStream client = new NamedPipeClientStream(".", "TestPipe", PipeDirection.InOut);
while(!client.IsConnected);
Streamreader reader = new StreamReader(client);
StreamWriter writer = new StreamWriter(client);
string line = "";
writer.AutoFlush = true;
while((line = reader.readLine()) != null) {
if(line.Contains("Hello!") {
writer.writeLine("1.2.3.4"); // input for the next prompt
}
else if(line.Contains("Text1") {
writer.writeLine("2.3.4.5"); // input for next prompt of Text2
}
writer.Flush();
writer.WaitForPipeDrain();
}
}
}
Is above the right way?
Also, sometimes the pipe reader is missing data. Like it shows Tet1 instead of Text1. Why such?

You have this statement: while(!client.IsConnected); which causes the client to wait for the connection before proceeding. However, the client never attempts to connect (client.Connect();), so presumably you will be waiting forever. Replace that line with if (!client.IsConnected) {client.Connect();} to get this to work.
Beyond that, per the comments, without knowing what your server side code looks like it's hard to say what the client should be sending; as the two sides are having a scripted conversation.
Here's an example of some working server & client code to illustrate how you could perform this conversation:
Code to kick off both client & server:
static void Main()
{
var server = Task.Factory.StartNew(() => RunServer());
var client = Task.Factory.StartNew(() => RunClient());
Task.WaitAll(server, client);
Console.WriteLine("Done");
}
Client code:
static void RunClient()
{
using (var pipeClient = new NamedPipeClientStream(".", "TestPipe", PipeDirection.InOut))
{
Console.WriteLine("Client is waiting to connect");
if(!pipeClient.IsConnected){pipeClient.Connect();}
Console.WriteLine("Client is connected");
using (var reader = new StreamReader(pipeClient))
{
using (var writer = new StreamWriter(pipeClient))
{
var running = true;
while(running)
{
Console.WriteLine("Client is waiting for input");
var message = reader.ReadLine();
if (message != null)
{
Console.WriteLine("Client: Recieved from server {0}", message);
switch (message)
{
case "Do you accept (y/n):":
writer.WriteLine("y");
writer.WriteLine("quit");
writer.Flush();
break;
case "quit":
running = false;
break;
}
}
}
}
}
}
Console.WriteLine("Client Quits");
}
Server code:
static void RunServer()
{
using (var pipeServer = new NamedPipeServerStream("TestPipe", PipeDirection.InOut))
{
using (var reader = new StreamReader(pipeServer))
{
using (var writer = new StreamWriter(pipeServer))
{
var running = true;
Console.WriteLine("Server is waiting for a client");
pipeServer.WaitForConnection();
Console.WriteLine("Server has connection from client");
Console.WriteLine("Server: Saying Hi");
writer.WriteLine("Hello!");
Console.WriteLine("Server: Prompting for Input");
writer.WriteLine("Do you accept (y/n):");
writer.Flush();
while(running)
{
pipeServer.WaitForPipeDrain();
var message = reader.ReadLine();
Console.WriteLine("Server: Recieved from client {0}", message);
if (message.Equals("quit"))
{
writer.WriteLine("quit");
running = false;
}
}
}
}
}
Console.WriteLine("Server Quits");
}
Update
Amended code to read characters rather than lines; so we don't have to wait for a line break before seeing the server's messages.
//using System.Threading.Tasks;
//using System.IO.Pipes;
static void Main()
{
var server = Task.Factory.StartNew(() => RunServer());
var client = Task.Factory.StartNew(() => RunClient());
Task.WaitAll(server, client);
Console.WriteLine("Done");
}
static void RunClient()
{
using (var pipeClient = new NamedPipeClientStream(".", "TestPipe", PipeDirection.InOut))
{
Console.WriteLine("Client is waiting to connect");
if(!pipeClient.IsConnected){pipeClient.Connect();}
Console.WriteLine("Client is connected");
using (var reader = new StreamReader(pipeClient))
{
using (var writer = new StreamWriter(pipeClient))
{
var message = string.Empty;
var running = true;
while(running)
{
Console.WriteLine("Client is waiting for input");
var chr = reader.Read();
if (chr >= 32)
{
message = message + (char)chr;
Console.WriteLine("Client: Recieved from server {0}", message);
switch (message)
{
case "Do you accept (y/n):":
writer.WriteLine("y");
writer.WriteLine("quit");
writer.Flush();
break;
case "quit":
running = false;
break;
}
}
else {
message = string.Empty;
Console.WriteLine("Client: New Line Received from Server");
}
}
}
}
}
Console.WriteLine("Client Quits");
}
static void RunServer()
{
using (var pipeServer = new NamedPipeServerStream("TestPipe", PipeDirection.InOut))
{
using (var reader = new StreamReader(pipeServer))
{
using (var writer = new StreamWriter(pipeServer))
{
var running = true;
Console.WriteLine("Server is waiting for a client");
pipeServer.WaitForConnection();
Console.WriteLine("Server has connection from client");
Console.WriteLine("Server: Saying Hi");
writer.WriteLine("Hello!");
Console.WriteLine("Server: Prompting for Input");
writer.Write("Do you accept (y/n):"); //NB: This is a write, not a write line!
writer.Flush();
while(running)
{
pipeServer.WaitForPipeDrain();
var message = reader.ReadLine();
Console.WriteLine("Server: Recieved from client {0}", message);
switch (message)
{
case "quit":
writer.WriteLine("quit");
running = false;
break;
default:
writer.WriteLine("");
break;
}
}
}
}
}
Console.WriteLine("Server Quits");
}
So this is what your code should look like:
int charAsInt;
var line = string.Empty;
while(((charAsInt = reader.Read()) != -1)) {
if (charAsInt >= 32) { //is a displayable character
line = line + (char)charAsInt;
//your code to handle the lines
if(line.Contains("Hello!")) {
writer.WriteLine("1.2.3.4"); // input for the next prompt
} else if(line.Contains("Text1") {
writer.WriteLine("2.3.4.5"); // input for next prompt of Text2
}
writer.Flush();
//writer.WaitForPipeDrain();
} else { //is a control character
if (charAsInt == 10 || charAsInt == 13) { //carriage return or line feed; i.e. end of line
if (line.Length > 0) {
Debug.WriteLine("Last line read was {0}", line); //just so you can see info as it comes from the server
line = string.Empty;
}
}
}
}

Related

sr.ReadLine() isn't receiving data that is being sent

I am trying to implement an authentication method for my program. I have a server-side program that handles authentication:
class Program
{
static TcpListener listener = new TcpListener(9120);
public const string DECRYPT_KEY = "KObOBonONoinbOClHNKYJkgIKUFkjfKcvCYckcvBBCVKcbvHHCxthjcTJYBXJahjh";
static void Main(string[] args)
{
listener.Start();
while (true)
{
if (listener.Pending())
{
new Thread(TryAuthenticate).Start();
}
}
}
static void TryAuthenticate()
{
TcpClient needsAuth = listener.AcceptTcpClient();
StreamReader sr = new StreamReader(needsAuth.GetStream());
string line = sr.ReadLine();
if (!line.StartsWith("AUTH? ")) return;
StreamReader sr2 = new StreamReader("keys.pks");
string line2;
while ((line2 = sr2.ReadLine()) != null)
{
if (line == line2)
{
new StreamWriter(needsAuth.GetStream()).WriteLine("AFFIRMATIVE");
sr.Close();
}
}
sr2.Close();
needsAuth.Close();
}
}
And on the client-side I have this code:
class Authentication
{
public static bool Authenticate(string id)
{
if (id == "dEbUg2020") return true;
TcpClient client = new TcpClient("127.0.0.1", 9120);
StreamWriter sw = new StreamWriter(client.GetStream());
StreamReader sr = new StreamReader(client.GetStream());
sw.WriteLine("AUTH? " + id);
if (sr.ReadLine() == "AFFIRMATIVE")
{
sw.Close();
sr.Close();
client.Close();
return true;
}
else
{
sw.Close();
sr.Close();
client.Close();
return false;
}
}
}
I have tried debugging on both the client and the server side.
On the client-side, it starts hanging at if (sr.ReadLine() == "AFFIRMATIVE").
On the server-side, it starts hanging at string line = sr.ReadLine();.
I have done some research and it has told me that when sr.ReadLine() is expecting data but doesn't get any, it hangs until it does.
But I have sent data, and both the client/server hangs indefinitely until it crashes. I am stuck, does anyone know why this isn't working?
After writing a message with your sw StreamWriter, you need to flush it with sw.Flush(); for it to actually be sent to the other side.
So
sw.WriteLine("Some line");
sw.Flush();
Otherwise, you're not sending anything.

UWP app cannot receive, only send, using sockets

I'm currently developing an UWP app which should have capability to be as a TCP server (using ports) so client can connect to it via other device and send requests and server responds with data.
I followed the Socket example on :Microsoft site, and got sample code working (in which server and client are both in same app)
I changed IP addresses and ports so i could use apps on 2 different machines with direct connection, I also made separate simple client application, using sample code from Here
Now problem is as follows: UWP app can successfully communicate with its own client method provided by Microsoft's sample, but is unable to communicate with console client program I made and was running on other. UWP can indeed connect with client and also send data, but it cannot receive data, the function streamReader.ReadLineAsync(); will wait infinitely long and that's all.
How do i make UWP app get the message client is sending and what i might be doing wrong ?
public sealed partial class MainPage : Page
{
static string PORT_NO = "1300";
const string SERVER_IP = "192.168.0.10";
public MainPage()
{
this.InitializeComponent();
outputText.Text = "Helloo";
StartConnection(SERVER_IP, PORT_NO);
//StartClient();
}
public async void StartConnection(string net_aadress, string port_nr)
{
try
{
var streamSocketListener = new StreamSocketListener();
// The ConnectionReceived event is raised when connections are received.
streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;
// Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
await streamSocketListener.BindServiceNameAsync(port_nr);
outputText.Text = "server is listening...";
}
catch (Exception ex)
{
Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
outputText.Text = (webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
}
}
private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
{
string request = "password";
string second;
/*
using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
{
request = await streamReader.ReadLineAsync();
}
*/
//await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add(string.Format("server received the request: \"{0}\"", request)));
// Echo the request back as the response.
using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite())
{
using (var streamWriter = new StreamWriter(outputStream))
{
await streamWriter.WriteLineAsync(request);
await streamWriter.FlushAsync();
}
}
using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
{
second = await streamReader.ReadLineAsync();
}
using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite())
{
using (var streamWriter = new StreamWriter(outputStream))
{
await streamWriter.WriteLineAsync(second);
await streamWriter.FlushAsync();
}
}
//await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add(string.Format("server sent back the response: \"{0}\"", request)));
sender.Dispose();
//await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add("server closed its socket"));
}
private async void StartClient()
{
try
{
// Create the StreamSocket and establish a connection to the echo server.
using (var streamSocket = new Windows.Networking.Sockets.StreamSocket())
{
// The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process.
var hostName = new Windows.Networking.HostName("localhost");
//this.clientListBox.Items.Add("client is trying to connect...");
await streamSocket.ConnectAsync(hostName, PORT_NO);
//this.clientListBox.Items.Add("client connected");
// Send a request to the echo server.
string request = "Hello, World!";
using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite())
{
using (var streamWriter = new StreamWriter(outputStream))
{
await streamWriter.WriteLineAsync(request);
await streamWriter.FlushAsync();
}
}
//this.clientListBox.Items.Add(string.Format("client sent the request: \"{0}\"", request));
// Read data from the echo server.
string response;
using (Stream inputStream = streamSocket.InputStream.AsStreamForRead())
{
using (StreamReader streamReader = new StreamReader(inputStream))
{
response = await streamReader.ReadLineAsync();
}
}
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
outputText.Text = "Client got back " + response;
}
);
}
//this.clientListBox.Items.Add("client closed its socket");
}
catch (Exception ex)
{
Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
//this.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
}
}
}
Here is source code for Client application:
{
class Program
{
const int PORT_NUMBER = 1300;
const string SERVER_IP = "192.168.0.10";
static void Main(string[] args)
{
string textToSend = DateTime.Now.ToString();
string password = "Madis on loll";
string receiveddata;
try
{
Console.WriteLine("Client progrm started");
TcpClient client = new TcpClient(SERVER_IP, PORT_NUMBER);
NetworkStream nwStream = client.GetStream();
//System.Threading.Thread.Sleep(500);
//see, how long is packet
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
byte[] password2 = ASCIIEncoding.ASCII.GetBytes(password);
Console.WriteLine("Sending : " + password);
nwStream.Write(password2, 0, password2.Length); //sending packet
byte[] receiveddata2 = new byte[client.ReceiveBufferSize];
int receiveddatalength = nwStream.Read(receiveddata2, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(receiveddata2, 0, bytesRead));
}
catch (Exception ex)
{
Console.WriteLine("Connection error");
}
}
}
}
Found answer myself: main problem is with ReadLineAsync() in Server program: it waits and collects all the stream until it gets end of line character. In this case end of line was never sent and therefore server kept waiting infinitely.
Simplest fix was on Client side by simply adding end of line at the end of packet, like this:
before:
byte[] password2 = ASCIIEncoding.ASCII.GetBytes(password);
Console.WriteLine("Sending : " + password);
nwStream.Write(password2, 0, password2.Length); //sending packet
after:
byte[] newLine = Encoding.ASCII.GetBytes(Environment.NewLine);
byte[] password2 = ASCIIEncoding.ASCII.GetBytes(password);
Console.WriteLine("Sending : " + password);
nwStream.Write(password2, 0, password2.Length); //sending packet
nwStream.Write(newLine,0,newLine.Length);
Also 1 thing worth mentioning: current StreamSocketListener_ConnectionReceived is able to send only once, then it sets outputStream.CanWrite to false.
This can be solved by removing using() from writing and reading functions, like this:
before:
PS! Manually flushing is also replaced with autoflush.
using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite())
{
using (var streamWriter = new StreamWriter(outputStream))
{
await streamWriter.WriteLineAsync(request);
await streamWriter.FlushAsync();
}
}
after:
Stream outputStream = args.Socket.OutputStream.AsStreamForWrite();
var streamWriter = new StreamWriter(outputStream);
streamWriter.AutoFlush = true;
await streamWriter.WriteLineAsync(request);
Hope it helps someone someday.

C# IRC Bot Error: 'Cannot read from a closed text reader'

I used this code once before, and it worked. Now, every time it tries to connect to an IRC server, I get the error: 'Cannot read from a closed text reader'
I've changed the adresses for privacy
This is my code:
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace IRCBot
{
class Program
{
}
class IrcBot
{
// Irc server to connect
public static string SERVER = "irc.rizon.net";
// Irc server's port (6667 is default port)
private static int PORT = 6660;
// User information defined in RFC 2812 (Internet Relay Chat: Client Protocol) is sent to irc server
private static string USER = "irc_bot";
// Bot's nickname
private static string NICK = "BotNick";
// Channel to join
private static string CHANNEL = "#testing";
// StreamWriter is declared here so that PingSender can access it
public static StreamWriter writer;
static void Main(string[] args)
{
NetworkStream stream;
TcpClient irc;
string inputLine;
StreamReader reader;
string nickname;
try
{
irc = new TcpClient(SERVER, PORT);
stream = irc.GetStream();
reader = new StreamReader(stream);
writer = new StreamWriter(stream);
// Start PingSender thread
PingSender ping = new PingSender();
ping.Start();
writer.WriteLine(USER);
writer.Flush();
writer.WriteLine("NICK " + NICK);
writer.Flush();
writer.WriteLine("JOIN " + CHANNEL);
writer.Flush();
while (true)
{
while ((inputLine = reader.ReadLine()) != null)
{
if (inputLine.EndsWith("JOIN :" + CHANNEL))
{
// Parse nickname of person who joined the channel
nickname = inputLine.Substring(1, inputLine.IndexOf("!") - 1);
// Welcome the nickname to channel by sending a notice
writer.WriteLine("NOTICE " + nickname + " :Hi " + nickname +
" and welcome to " + CHANNEL + " channel!");
writer.Flush();
// Sleep to prevent excess flood
Thread.Sleep(2000);
}
}
// Close all streams
writer.Close();
reader.Close();
irc.Close();
}
}
catch (Exception e)
{
// Show the exception, sleep for a while and try to establish a new connection to irc server
Console.WriteLine(e.ToString());
Thread.Sleep(5000);
string[] argv = { };
Main(argv);
}
}
}
class PingSender
{
static string PING = "PING :";
private Thread pingSender;
// Empty constructor makes instance of Thread
public PingSender()
{
pingSender = new Thread(new ThreadStart(this.Run));
}
// Starts the thread
public void Start()
{
pingSender.Start();
}
// Send PING to irc server every 15 seconds
public void Run()
{
while (true)
{
IrcBot.writer.WriteLine(PING + IrcBot.SERVER);
IrcBot.writer.Flush();
Thread.Sleep(15000);
}
}
}
}
Close all streams must be outside while:
while (true)
{
while ((inputLine = reader.ReadLine()) != null)
{
....
}
}
// Close all streams
writer.Close();
reader.Close();
irc.Close();
Move all your stream closing lines to "finally" block:
try
{
...
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Thread.Sleep(5000);
string[] argv = { };
Main(argv);
}
finally
{
//Close all streams
writer?.Close();
reader?.Close();
irc?.Close();
}
Note, I've used new C#6 null-propagation operator ?. here cause your streams can be null. If you're using C# ver<6 then write it like this:
if (writer!=null) writer.Close();

Auto flush of tcp stream doesn't work

As you may see I work a little SMTP server written in C#.
I included whole code (one class is not included), but I hope you get good view of detail.
I am struggeling at the DATA post from the client, the problem is in my point of view the not working "Auto Flush".
The client sends to my server "DATA" to tell me to get ready to receive data for my email.
I need to answer "354 start mail input", which I do, my problem is:
After sending "354 start mail input" I need to receive the message from client in this funtion.
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace FakeSMTP
{
public class SMTPServer //: IDisposable
{
TcpClient client;
NetworkStream stream;
System.IO.StreamReader reader;
System.IO.StreamWriter writer;
//public void Dispose()
//{
// writer.Dispose();
// reader.Dispose();
// stream.Dispose();
//}
public SMTPServer(TcpClient client)
{
this.client = client;
stream = client.GetStream();
reader = new System.IO.StreamReader(stream);
writer = new System.IO.StreamWriter(stream);
writer.NewLine = "\r\n";
writer.AutoFlush = true;
}
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Loopback, 25);
listener.Start();
//using (SMTPServer handler = new SMTPServer(listener.AcceptTcpClient()))
while (true)
{
SMTPServer handler = new SMTPServer(listener.AcceptTcpClient());
Thread thread = new System.Threading.Thread(new ThreadStart(handler.Run));
thread.Start();
}
}
public void Run()
{
string sadress;
string radress;
string rserver;
bool auth = false;
writer.WriteLine("220 smtp.localsmtp.de ESMTP server ready");
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
Console.Error.WriteLine("Read line {0}", line);
if (line.StartsWith("EHLO"))
{
writer.WriteLine("250-smtp.localsmtp.de");
//Auth ankuendigen
writer.WriteLine("250 AUTH PLAIN");
}
if (line.StartsWith("QUIT"))
{
writer.WriteLine("221 Bye Sweetie see ya");
client.Close();
}
#region auth
if (line.StartsWith("AUTH PLAIN"))
{
Console.WriteLine("client sendet Auth: " + line);
string [] pw = line.Split(new string[] { "PLAIN " }, StringSplitOptions.None);
byte[] bytes = Convert.FromBase64String(pw[1]);
string result = Encoding.BigEndianUnicode.GetString(bytes);
if (result == "12")
{
writer.WriteLine("235 2.7.0 Authentication successful");
auth = true;
}
else
{
Console.WriteLine("Falsche AUTH Daten");
writer.WriteLine("535 – Incorrect authentication data");
}
}
#endregion
#region sender
if (line.StartsWith("MAIL FROM") && auth == true)
{
string[] sadressa = line.Split(new string[] { "FROM:" }, StringSplitOptions.None);
sadress = sadressa[1];
//Absender
sadress = sadress.Replace("<","").Replace(">","");
//Debug
Console.WriteLine("Absender: " + sadress);
writer.WriteLine("250 OK");
}
#endregion
#region receiver
if (line.StartsWith("RCPT TO:") && auth == true)
{
string[] radressa = line.Split(new string[] { "RCPT TO:" }, StringSplitOptions.None);
radress = radressa[1];
//Empfänger
radress = radress.Replace("<", "").Replace(">", "");
if (samplesmtp.getMX.GetMXRecord(radress) != "invalid")
{
rserver = samplesmtp.getMX.GetMXRecord(radress);
Console.WriteLine("MX Record: " + rserver);
}
else
Console.WriteLine("ALARM");
//Debug
Console.WriteLine("Empfänger: " + radress);
writer.WriteLine("250 OK");
}
#endregion
#region data
if (line.StartsWith("DATA") && auth == true)
{
writer.WriteLine("354 start mail input");
var emailLine = reader.ReadLine();
while (!emailLine.Equals("."))
{
// add emailLine to the email body
string[] emailbody = new string[] {emailLine};
Console.WriteLine("Emailbody: " + emailbody[0]);
}
reader.Close();
writer.Close();
stream.Dispose();
writer.WriteLine("250 OK");
}
#endregion
}
}
}
}
Trying to call .Flush() manually in code doesn't change the problem at all. No effect.
In answer to your actual question you want to read all the lines until you receive a . on a line on it's own (see https://www.ietf.org/rfc/rfc2821.txt), something like this: -
var emailLine = reader.ReadLine();
while (!emailLine.Equals("."))
{
// add emailLine to the email body
emailLine = reader.readLine();
}
writer.WriteLine("250 OK");
reader.Close();
writer.Close();
stream.Dispose();
In response to your comment to mine:
public class SMTPServer : IDisposable
{
// all the other stuff
public void Dispose()
{
writer.Dispose();
reader.Dispose();
stream.Dispose();
}
}
calling code:
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Loopback, 25);
listener.Start();
using (SMTPServer handler = new SMTPServer(listener.AcceptTcpClient()))
{
while (true)
{
Thread thread = new System.Threading.Thread(new ThreadStart(handler.Run));
thread.Start();
}
}
}

Determine if NamedPipeClientStream is connected

I've problem with process communication using PipeConnection
My idea is:
A - process A
B - process B
1. A(pile client) wants to send message to B(pipe server)
2. B reads message and disconects.
2.1 If B needs to ansver
2.2 B(pipe client) connects to A(pile server)
2.3 A reads message and disconects.
The problem appears if A sends message to B and than imedlitley wants to send another message again
Code sample:
//Server
static void Main(string[] args)
{
using (NamedPipeServerStream server = new NamedPipeServerStream("EOG", PipeDirection.In))
{
StreamReader sr = new StreamReader(server);
while (true)
{
server.WaitForConnection();
Console.WriteLine("Conected to client");
try
{
Console.WriteLine(sr.ReadLine());
server.Disconnect();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
sr.Dispose();
}
}
}
//Client
static void Main(string[] args)
{
using (NamedPipeClientStream client = new NamedPipeClientStream(".", "EOG", PipeDirection.Out))
{
StreamWriter sw = new StreamWriter(client);
while (true)
{
Console.WriteLine("Message: ");
sw.WriteLine(Console.ReadLine());
if (!client.IsConnected)
client.Connect();
sw.Flush();
}
sw.Dispose();
}
Console.ReadKey();
}

Categories

Resources