Post

PipesClient

A named pipe client that sends messages to and receives messages from a PipesServer.


Remarks

The PipesClient class wraps around the NamedPipeClientStream class. Each PipesClient establishes a single pipe between itself and a PipesServer, allowing messages to be both received and sent. If the server goes down or is not available, the client reverts to a listening state, and reconnects when the server comes back online.


Constructors

SyntaxDescription
PipesClient(string pID, string sID = “.”)PipesClient constructor. pID should match the ID of the server. sID defaults to “.”, indicating a local server; otherwise provide the network ID.

Properties

IdentifierTypeDescription
AutoReconnectboolIndicates if the client should attempt to reconnect upon a broken pipe.

Events

IdentifierTypeDescription
DisconnectedPipeConnectionEventIndicate disconnection event.
ErrorPipeExceptionEventHandlerIndicate error occurred.
ServerMessagePipeConnectionMessageEventIndicate message received from server.

Methods

MethodReturnsDescription
Send(PipeMessage message)voidSends a message to the server.
Start()voidStarts the client.
Stop()voidStop the client, and do not attempt to reconnect.
WaitForConnection(int ms)voidBlocks until the client has connected to the server, or the timeout elapses.
WaitForDisconnection(int ms)voidBlocks until the client has disconnected from the server, or the timeout elapses.

Delegates

DelegateReturnsDescription
PipeExceptionEventHandler(Exception exception)voidHandles an error raised by a pipes client or server.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using Nova.IPC.Pipes;
using System.IO;

public class PipeClient
{

  private PipesClient client;

  public PipeClient(string pipeName)
  {
    client = new PipesClient(pipeName);
    client.ServerMessage += OnServerMessage;
    client.Error += OnError;
    client.Start();
    while (KeepRunning)
    {
      // Do nothing - wait for user to press 'q' key
    }
    client.Stop();
  }

  // Receives console key input from user.
  private bool KeepRunning
  {
    get
    {
      var key = Console.ReadKey();
      if (key.Key == ConsoleKey.Q) return false;
      else if (key.Key == ConsoleKey.S)
      {
        PipeMessage pm = new PipeMessage();
        pm.EncodeString("Hello!");
        client.Send(pm);
      }
      return true;
    }
  }

  public static void Main()
  {
    Console.WriteLine("Running in CLIENT mode");
    Console.WriteLine("Press 's' to send a string message to the server");
    Console.WriteLine("Press 'q' to exit");
    new PipeClient("TestServer");
  }

  private void OnServerMessage(PipesConnection connection, PipeMessage message)
  {
    switch (message.MsgCode)
    {
      case '0': 
        Console.WriteLine("Server says: {0}", message.DecodeString());
        break;
      case '1':
        SomeObject obj = new SomeObject();
        obj.Deserialize(message.MsgData);
        PrintMessage(obj);
        break;
      default:
        Console.WriteLine("Server sent unrecognized message code: {0}",message.MsgCode);
        break;
    }
    
  }

  private void OnError(Exception exception)
  {
    Console.Error.WriteLine("ERROR: {0}", exception);
  }

  private void PrintMessage(SomeObject obj)
  {
    Console.WriteLine("SomeObject int:    " + obj.intData.ToString());
    Console.WriteLine("SomeObject double: " + obj.doubleData.ToString());
    Console.WriteLine("SomeObject string: " + obj.strData);
  }
  
}

// Stands in for your own message payload type.
public class SomeObject
{
  public int intData = 1;
  public double doubleData = 2.5;
  public string strData = "three";

  public byte[] Serialize()
  {
    using (MemoryStream stream = new MemoryStream())
    using (BinaryWriter writer = new BinaryWriter(stream))
    {
      writer.Write(intData);
      writer.Write(doubleData);
      writer.Write(strData);
      return stream.ToArray();
    }
  }

  public void Deserialize(byte[] data)
  {
    using (BinaryReader reader = new BinaryReader(new MemoryStream(data)))
    {
      intData = reader.ReadInt32();
      doubleData = reader.ReadDouble();
      strData = reader.ReadString();
    }
  }
}
This post is licensed under CC BY 4.0 by the author.

Trending Tags