// ver 1.1
using System;
namespace Communication.Pipe
{
class Client
{
#region vars
#region DllImport
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
public static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFile(
String pipeName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplate);
public const uint GENERIC_READ = (0x80000000);
public const uint GENERIC_WRITE = (0x40000000);
public const uint OPEN_EXISTING = 3;
public const uint FILE_FLAG_OVERLAPPED = (0x40000000);
#endregion ---DllImport---
public delegate void MessageReceivedHandler(string message);
public event MessageReceivedHandler MessageReceived;
public const int BUFFER_SIZE = 4096;
char delineator = (char)13;
string pipeName= "\\\\.\\pipe\\Spike0001";
private System.IO.FileStream stream;
private Microsoft.Win32.SafeHandles.SafeFileHandle handle;
System.Threading.Thread readThread;
bool connected;
int maxConnectionTrys = 5;
public bool Connected
{
get { return this.connected; }
}
public string PipeName
{
get { return this.pipeName; }
set { this.pipeName = value; }
}
#endregion ---vars---
#region Connect
///
/// Connects to the server
///
public bool Connect()
{
this.handle =
CreateFile(
this.pipeName,
GENERIC_READ | GENERIC_WRITE,
0,
IntPtr.Zero,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
IntPtr.Zero);
//could not create handle - server probably not running
if (this.handle.IsInvalid)
return false;
this.connected = true;
//start listening for messages
this.readThread = new System.Threading.Thread(new System.Threading.ThreadStart(Read));
this.readThread.Start();
readThread.IsBackground = true;
return true;
}
#endregion ---Connect---
#region Read
///
/// Reads data from the server
///
public void Read()
{
this.stream = new System.IO.FileStream(this.handle, System.IO.FileAccess.ReadWrite, BUFFER_SIZE, true);
byte[] readBuffer = new byte[BUFFER_SIZE];
System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
while (true)
{
int bytesRead = 0;
try
{
bytesRead = this.stream.Read(readBuffer, 0, BUFFER_SIZE);
}
catch
{
//read error occurred
break;
}
//server has disconnected
if (bytesRead == 0)
break;
//fire message received event
if (this.MessageReceived != null)
this.MessageReceived(encoder.GetString(readBuffer, 0, bytesRead));
}
//clean up resource
this.stream.Close();
this.handle.Close();
}
#endregion ---Read---
#region send to Server
///
/// Sends a message to the server
///
/// message to send
/// true for sucess, false for error
public bool SendMessage(string message)
{
try
{
System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
byte[] messageBuffer = encoder.GetBytes(message + delineator);
this.stream.Write(messageBuffer, 0, messageBuffer.Length);
this.stream.Flush();
return true;
}
catch
{
return false;
}
}
///
/// Send a Object to the server
///
///
public void SendObject(object objIN)
{
try
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.Reflection.PropertyInfo p in objIN.GetType().GetProperties())
{
object val = p.GetValue(objIN, null);
sb.Append(p.Name + "=" + val.ToString() + delineator);
}
// send message
bool SentMessage = SendMessage(sb.ToString());
if (!SentMessage)
{
SendObject(objIN, new Random().Next(2000), 0);
}
}
catch
{
throw new Exception("Fail To Send #j67jt67j");
}
}
///
/// Send Object to server, fail retry
///
/// Object to send
/// Back off try
public void SendObject(object objIN, int backOff, int tryCount)
{
if (tryCount > maxConnectionTrys)
return;
try
{
System.Threading.Thread.Sleep(backOff);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.Reflection.PropertyInfo p in objIN.GetType().GetProperties())
{
object val = p.GetValue(objIN, null);
sb.Append(p.Name + "=" + val.ToString() + delineator);
}
// send message
bool SentMessage = SendMessage(sb.ToString());
if (!SentMessage)
{
SendObject(objIN, new Random().Next(2000), tryCount + 1);
}
}
catch
{
throw new Exception("Fail To Send #uidhsi9f");
}
}
#endregion ---send to Server---
}
}