chuckd

chuckd
- Name: [not set]
- Favorite Languages: [not set]
- Website: [not set]
- Location: [not set]
- About Me: [not set]
-
Interprocess Communication using Named Pipes in C#
06/16/2009 - 16:06
got it...use 3.5
-
Interprocess Communication using Named Pipes in C#
06/16/2009 - 13:32
I'm using this example for some interprocessing between a VB6.exe and C#.exe.
I have compiled the server app into C# interop .dll so it can be utilized in VB6. VB6 then starts the server through this .dll.
I then a have a C# client that is waiting for messages.
However, in the SendMessage portion of the C# server .dll sometimes my clients are null. Even though I can confirm that a client is added during the 'ListenForClients'.
What am I missing here.
private void ListenForClients()
{
bool clientConnected = false;
while (!clientConnected)
{
SafeFileHandle clientHandle =
CreateNamedPipe(
this.pipeName,
DUPLEX | FILE_FLAG_OVERLAPPED,
0,
255,
BUFFER_SIZE,
BUFFER_SIZE,
0,
IntPtr.Zero);
//could not create named pipe
if (clientHandle.IsInvalid)
return;
int success = ConnectNamedPipe(clientHandle, IntPtr.Zero);
//could connect client
if (success == 1)
{
clientConnected = true;
//handling multiple clients
Client client = new Client();
client.handle = clientHandle;
lock (clients)
this.clients.Add(client);
this.readThread = new Thread(new ParameterizedThreadStart(Read));
readThread.IsBackground = true;
readThread.Start(client);
}
else
{
clientConnected = false;
}
}
}
/// <summary>
/// Reads incoming data from connected clients
/// </summary>
/// <param name="clientObj"></param>
///
private void Read(object clientObj)
{
client = (Client)clientObj;
client.stream = new FileStream(client.handle, FileAccess.ReadWrite, BUFFER_SIZE, true);
byte[] buffer = new byte[BUFFER_SIZE];
ASCIIEncoding encoder = new ASCIIEncoding();
while (!_shutdown)
{
int bytesRead = 0;
try
{
bytesRead = client.stream.Read(buffer, 0, BUFFER_SIZE);
}
catch
{
//read error has occurred
break;
}
//client has disconnected
if (bytesRead == 0)
break;
//fire message received event
Console.WriteLine(encoder.GetString(buffer, 0, bytesRead));
}
//clean up resources
client.stream.Close();
client.handle.Close();
lock (this.clients)
this.clients.Remove(client);
}
/// <summary>
/// Sends a message to all connected clients
/// </summary>
/// <param name="message">the message to send</param>
public void SendMessage(string message)
{
lock (this.clients)
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] messageBuffer = encoder.GetBytes(message);
foreach (Client client in this.clients)
{
client.stream.Write(messageBuffer, 0, messageBuffer.Length);
client.stream.Flush();
}
}
}
}
}
Recent Comments