You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

758 lines
40 KiB

3 months ago
  1. # @achrinza/node-ipc
  2. > **NOTE:** This is a maintenance fork of `node-ipc` This is intended for
  3. > packages that directly or indirectly depend on `node-ipc` where maintainers
  4. > need a drop-in replacement.
  5. >
  6. > See https://github.com/achrinza/node-ipc/issues/1 for more details.
  7. [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](code_of_conduct.md)
  8. [![Coverage Status](https://coveralls.io/repos/github/achrinza/node-ipc/badge.svg?branch=main)](https://coveralls.io/github/achrinza/node-ipc?branch=main)
  9. _a nodejs module for local and remote Inter Process Communication_ with full support for Linux, Mac and Windows. It also supports all forms of socket communication from low level unix and windows sockets to UDP and secure TLS and TCP sockets.
  10. A great solution for complex multiprocess **Neural Networking** in Node.JS
  11. **npm install @achrinza/node-ipc**
  12. #### Older versions of node
  13. the latest versions of `@achrinza/node-ipc` may work with the --harmony flag. Officially though, we support node v4 and newer with es5 and es6
  14. #### Testing
  15. `npm test` will run the jasmine tests with istanbul for @achrinza/node-ipc and generate a coverage report in the spec folder.
  16. You may want to install jasmine and istanbul globally with `sudo npm install -g jasmine istanbul`
  17. ---
  18. #### Contents
  19. 1. [Types of IPC Sockets and Supporting OS](#types-of-ipc-sockets)
  20. 1. [IPC Config](#ipc-config)
  21. 1. [IPC Methods](#ipc-methods)
  22. 1. [log](#log)
  23. 2. [connectTo](#connectto)
  24. 3. [connectToNet](#connecttonet)
  25. 4. [disconnect](#disconnect)
  26. 5. [serve](#serve)
  27. 6. [serveNet](#servenet)
  28. 1. [IPC Stores and Default Variables](#ipc-stores-and-default-variables)
  29. 1. [IPC Events](#ipc-events)
  30. 1. [Multiple IPC instances](#multiple-ipc-instances)
  31. 1. [Basic Examples](#basic-examples)
  32. 1. [Server for Unix||Windows Sockets & TCP Sockets](#server-for-unix-sockets-windows-sockets--tcp-sockets)
  33. 2. [Client for Unix||Windows Sockets & TCP Sockets](#client-for-unix-sockets--tcp-sockets)
  34. 3. [Server & Client for UDP Sockets](#server--client-for-udp-sockets)
  35. 4. [Raw Buffers, Real Time and / or Binary Sockets](#raw-buffer-or-binary-sockets)
  36. 1. [Working with TLS/SSL Socket Servers & Clients](https://github.com/RIAEvangelist/@achrinza/node-ipc/tree/master/example/TLSSocket)
  37. 1. [Node Code Examples](https://github.com/RIAEvangelist/@achrinza/node-ipc/tree/master/example)
  38. ---
  39. #### Types of IPC Sockets
  40. | Type | Stability | Definition |
  41. | ----------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  42. | Unix Socket or Windows Socket | Stable | Gives Linux, Mac, and Windows lightning fast communication and avoids the network card to reduce overhead and latency. [Local Unix and Windows Socket examples ](https://github.com/RIAEvangelist/@achrinza/node-ipc/tree/master/example/unixWindowsSocket/ "Unix and Windows Socket Node IPC examples") |
  43. | TCP Socket | Stable | Gives the most reliable communication across the network. Can be used for local IPC as well, but is slower than #1's Unix Socket Implementation because TCP sockets go through the network card while Unix Sockets and Windows Sockets do not. [Local or remote network TCP Socket examples ](https://github.com/RIAEvangelist/@achrinza/node-ipc/tree/master/example/TCPSocket/ "TCP Socket Node IPC examples") |
  44. | TLS Socket | Stable | Configurable and secure network socket over SSL. Equivalent to https. [TLS/SSL documentation](https://github.com/RIAEvangelist/@achrinza/node-ipc/tree/master/example/TLSSocket) |
  45. | UDP Sockets | Stable | Gives the **fastest network communication**. UDP is less reliable but much faster than TCP. It is best used for streaming non critical data like sound, video, or multiplayer game data as it can drop packets depending on network connectivity and other factors. UDP can be used for local IPC as well, but is slower than #1's Unix Socket or Windows Socket Implementation because UDP sockets go through the network card while Unix and Windows Sockets do not. [Local or remote network UDP Socket examples ](https://github.com/RIAEvangelist/@achrinza/node-ipc/tree/master/example/UDPSocket/ "UDP Socket Node IPC examples") |
  46. | OS | Supported Sockets |
  47. | ----- | -------------------------- |
  48. | Linux | Unix, Posix, TCP, TLS, UDP |
  49. | Mac | Unix, Posix, TCP, TLS, UDP |
  50. | Win | Windows, TCP, TLS, UDP |
  51. ---
  52. #### IPC Config
  53. `ipc.config`
  54. Set these variables in the `ipc.config` scope to overwrite or set default values.
  55. ```javascript
  56. {
  57. appspace : 'app.',
  58. socketRoot : '/tmp/',
  59. id : os.hostname(),
  60. networkHost : 'localhost', //should resolve to 127.0.0.1 or ::1 see the table below related to this
  61. networkPort : 8000,
  62. readableAll : false,
  63. writableAll : false,
  64. encoding : 'utf8',
  65. rawBuffer : false,
  66. delimiter : '\f',
  67. sync : false,
  68. silent : false,
  69. logInColor : true,
  70. logDepth : 5,
  71. logger : console.log,
  72. maxConnections : 100,
  73. retry : 500,
  74. maxRetries : false,
  75. stopRetrying : false,
  76. unlink : true,
  77. interfaces : {
  78. localAddress: false,
  79. localPort : false,
  80. family : false,
  81. hints : false,
  82. lookup : false
  83. }
  84. }
  85. ```
  86. | variable | documentation |
  87. | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  88. | appspace | used for Unix Socket (Unix Domain Socket) namespacing. If not set specifically, the Unix Domain Socket will combine the socketRoot, appspace, and id to form the Unix Socket Path for creation or binding. This is available in case you have many apps running on your system, you may have several sockets with the same id, but if you change the appspace, you will still have app specic unique sockets. |
  89. | socketRoot | the directory in which to create or bind to a Unix Socket |
  90. | id | the id of this socket or service |
  91. | networkHost | the local or remote host on which TCP, TLS or UDP Sockets should connect |
  92. | networkPort | the default port on which TCP, TLS, or UDP sockets should connect |
  93. | readableAll | makes the pipe readable for all users including windows services |
  94. | writableAll | makes the pipe writable for all users including windows services |
  95. | encoding | the default encoding for data sent on sockets. Mostly used if rawBuffer is set to true. Valid values are : ` ascii` `utf8` ` utf16le` ` ucs2` ` base64` `hex` . |
  96. | rawBuffer | if true, data will be sent and received as a raw node `Buffer` **NOT** an `Object` as JSON. This is great for Binary or hex IPC, and communicating with other processes in languages like C and C++ |
  97. | delimiter | the delimiter at the end of each data packet. |
  98. | sync | synchronous requests. Clients will not send new requests until the server answers. |
  99. | silent | turn on/off logging default is false which means logging is on |
  100. | logInColor | turn on/off util.inspect colors for ipc.log |
  101. | logDepth | set the depth for util.inspect during ipc.log |
  102. | logger | the function which receives the output from ipc.log; should take a single string argument |
  103. | maxConnections | this is the max number of connections allowed to a socket. It is currently only being set on Unix Sockets. Other Socket types are using the system defaults. |
  104. | retry | this is the time in milliseconds a client will wait before trying to reconnect to a server if the connection is lost. This does not effect UDP sockets since they do not have a client server relationship like Unix Sockets and TCP Sockets. |
  105. | maxRetries | if set, it represents the maximum number of retries after each disconnect before giving up and completely killing a specific connection |
  106. | stopRetrying | Defaults to false meaning clients will continue to retry to connect to servers indefinitely at the retry interval. If set to any number the client will stop retrying when that number is exceeded after each disconnect. If set to true in real time it will immediately stop trying to connect regardless of maxRetries. If set to 0, the client will **_NOT_** try to reconnect. |
  107. | unlink | Defaults to true meaning that the module will take care of deleting the IPC socket prior to startup. If you use `@achrinza/node-ipc` in a clustered environment where there will be multiple listeners on the same socket, you must set this to `false` and then take care of deleting the socket in your own code. |
  108. | interfaces | primarily used when specifying which interface a client should connect through. see the [socket.connect documentation in the node.js api](https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener) |
  109. ---
  110. #### IPC Methods
  111. These methods are available in the IPC Scope.
  112. ---
  113. ##### log
  114. `ipc.log(a,b,c,d,e...);`
  115. ipc.log will accept any number of arguments and if `ipc.config.silent` is not set, it will concat them all with a single space ' ' between them and then log them to the console. This is fast because it prevents any concatenation from happening if the ipc.config.silent is set `true`. That way if you leave your logging in place it should have almost no effect on performance.
  116. The log also uses util.inspect You can control if it should log in color, the log depth, and the destination via `ipc.config`
  117. ```javascript
  118. ipc.config.logInColor = true; //default
  119. ipc.config.logDepth = 5; //default
  120. ipc.config.logger = console.log.bind(console); // default
  121. ```
  122. ---
  123. ##### connectTo
  124. `ipc.connectTo(id,path,callback);`
  125. Used for connecting as a client to local Unix Sockets and Windows Sockets. **_This is the fastest way for processes on the same machine to communicate_** because it bypasses the network card which TCP and UDP must both use.
  126. | variable | required | definition |
  127. | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
  128. | id | required | is the string id of the socket being connected to. The socket with this id is added to the ipc.of object when created. |
  129. | path | optional | is the path of the Unix Domain Socket File, if the System is Windows, this will automatically be converted to an appropriate pipe with the same information as the Unix Domain Socket File. If not set this will default to `ipc.config.socketRoot`+`ipc.config.appspace`+`id` |
  130. | callback | optional | this is the function to execute when the socket has been created. |
  131. **examples** arguments can be ommitted so long as they are still in order.
  132. ```javascript
  133. ipc.connectTo("world");
  134. ```
  135. or using just an id and a callback
  136. ```javascript
  137. ipc.connectTo("world", function () {
  138. ipc.of.world.on("hello", function (data) {
  139. ipc.log(data.debug);
  140. //if data was a string, it would have the color set to the debug style applied to it
  141. });
  142. });
  143. ```
  144. or explicitly setting the path
  145. ```javascript
  146. ipc.connectTo("world", "myapp.world");
  147. ```
  148. or explicitly setting the path with callback
  149. ```javascript
  150. ipc.connectTo(
  151. 'world',
  152. 'myapp.world',
  153. function(){
  154. ...
  155. }
  156. );
  157. ```
  158. ---
  159. ##### connectToNet
  160. `ipc.connectToNet(id,host,port,callback)`
  161. Used to connect as a client to a TCP or [TLS socket](https://github.com/RIAEvangelist/@achrinza/node-ipc/tree/master/example/TLSSocket) via the network card. This can be local or remote, if local, it is recommended that you use the Unix and Windows Socket Implementaion of `connectTo` instead as it is much faster since it avoids the network card altogether.
  162. For TLS and SSL Sockets see the [@achrinza/node-ipc TLS and SSL docs](https://github.com/RIAEvangelist/@achrinza/node-ipc/tree/master/example/TLSSocket). They have a few additional requirements, and things to know about and so have their own doc.
  163. | variable | required | definition |
  164. | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  165. | id | required | is the string id of the socket being connected to. For TCP & TLS sockets, this id is added to the `ipc.of` object when the socket is created with a reference to the socket. |
  166. | host | optional | is the host on which the TCP or TLS socket resides. This will default to `ipc.config.networkHost` if not specified. |
  167. | port | optional | the port on which the TCP or TLS socket resides. |
  168. | callback | optional | this is the function to execute when the socket has been created. |
  169. **examples** arguments can be ommitted so long as they are still in order.
  170. So while the default is : (id,host,port,callback), the following examples will still work because they are still in order (id,port,callback) or (id,host,callback) or (id,port) etc.
  171. ```javascript
  172. ipc.connectToNet("world");
  173. ```
  174. or using just an id and a callback
  175. ```javascript
  176. ipc.connectToNet(
  177. 'world',
  178. function(){
  179. ...
  180. }
  181. );
  182. ```
  183. or explicitly setting the host and path
  184. ```javascript
  185. ipc.connectToNet(
  186. 'world',
  187. 'myapp.com',serve(path,callback)
  188. 3435
  189. );
  190. ```
  191. or only explicitly setting port and callback
  192. ```javascript
  193. ipc.connectToNet(
  194. 'world',
  195. 3435,
  196. function(){
  197. ...
  198. }
  199. );
  200. ```
  201. ---
  202. ##### disconnect
  203. `ipc.disconnect(id)`
  204. Used to disconnect a client from a Unix, Windows, TCP or TLS socket. The socket and its refrence will be removed from memory and the `ipc.of` scope. This can be local or remote. UDP clients do not maintain connections and so there are no Clients and this method has no value to them.
  205. | variable | required | definition |
  206. | -------- | -------- | -------------------------------------------------------- |
  207. | id | required | is the string id of the socket from which to disconnect. |
  208. **examples**
  209. ```javascript
  210. ipc.disconnect("world");
  211. ```
  212. ---
  213. ##### serve
  214. `ipc.serve(path,callback);`
  215. Used to create local Unix Socket Server or Windows Socket Server to which Clients can bind. The server can `emit` events to specific Client Sockets, or `broadcast` events to all known Client Sockets.
  216. | variable | required | definition |
  217. | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  218. | path | optional | This is the path of the Unix Domain Socket File, if the System is Windows, this will automatically be converted to an appropriate pipe with the same information as the Unix Domain Socket File. If not set this will default to `ipc.config.socketRoot`+`ipc.config.appspace`+`id` |
  219. | callback | optional | This is a function to be called after the Server has started. This can also be done by binding an event to the start event like `ipc.server.on('start',function(){});` |
  220. **_examples_** arguments can be omitted so long as they are still in order.
  221. ```javascript
  222. ipc.serve();
  223. ```
  224. or specifying callback
  225. ```javascript
  226. ipc.serve(
  227. function(){...}
  228. );
  229. ```
  230. or specify path
  231. ```javascript
  232. ipc.serve("/tmp/myapp.myservice");
  233. ```
  234. or specifying everything
  235. ```javascript
  236. ipc.serve(
  237. '/tmp/myapp.myservice',
  238. function(){...}
  239. );
  240. ```
  241. ---
  242. ##### serveNet
  243. `serveNet(host,port,UDPType,callback)`
  244. Used to create TCP, TLS or UDP Socket Server to which Clients can bind or other servers can send data to. The server can `emit` events to specific Client Sockets, or `broadcast` events to all known Client Sockets.
  245. | variable | required | definition |
  246. | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  247. | host | optional | If not specified this defaults to the first address in os.networkInterfaces(). For TCP, TLS & UDP servers this is most likely going to be 127.0.0.1 or ::1 |
  248. | port | optional | The port on which the TCP, UDP, or TLS Socket server will be bound, this defaults to 8000 if not specified |
  249. | UDPType | optional | If set this will create the server as a UDP socket. 'udp4' or 'udp6' are valid values. This defaults to not being set. When using udp6 make sure to specify a valid IPv6 host, like `::1` |
  250. | callback | optional | Function to be called when the server is created |
  251. **_examples_** arguments can be ommitted solong as they are still in order.
  252. default tcp server
  253. ```javascript
  254. ipc.serveNet();
  255. ```
  256. default udp server
  257. ```javascript
  258. ipc.serveNet("udp4");
  259. ```
  260. or specifying TCP server with callback
  261. ```javascript
  262. ipc.serveNet(
  263. function(){...}
  264. );
  265. ```
  266. or specifying UDP server with callback
  267. ```javascript
  268. ipc.serveNet(
  269. 'udp4',
  270. function(){...}
  271. );
  272. ```
  273. or specify port
  274. ```javascript
  275. ipc.serveNet(3435);
  276. ```
  277. or specifying everything TCP
  278. ```javascript
  279. ipc.serveNet(
  280. 'MyMostAwesomeApp.com',
  281. 3435,
  282. function(){...}
  283. );
  284. ```
  285. or specifying everything UDP
  286. ```javascript
  287. ipc.serveNet(
  288. 'MyMostAwesomeApp.com',
  289. 3435,
  290. 'udp4',
  291. function(){...}
  292. );
  293. ```
  294. ---
  295. ### IPC Stores and Default Variables
  296. | variable | definition |
  297. | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  298. | ipc.of | This is where socket connection refrences will be stored when connecting to them as a client via the `ipc.connectTo` or `iupc.connectToNet`. They will be stored based on the ID used to create them, eg : ipc.of.mySocket |
  299. | ipc.server | This is a refrence to the server created by `ipc.serve` or `ipc.serveNet` |
  300. ---
  301. ### IPC Server Methods
  302. | method | definition |
  303. | ------ | --------------------------------------------------------------------------- |
  304. | start | start serving need to call `serve` or `serveNet` first to set up the server |
  305. | stop | close the server and stop serving |
  306. ---
  307. ### IPC Events
  308. | event name | params | definition |
  309. | --------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  310. | error | err obj | triggered when an error has occured |
  311. | connect | | triggered when socket connected |
  312. | disconnect | | triggered by client when socket has disconnected from server |
  313. | socket.disconnected | socket destroyedSocketID | triggered by server when a client socket has disconnected |
  314. | destroy | | triggered when socket has been totally destroyed, no further auto retries will happen and all references are gone. |
  315. | data | buffer | triggered when ipc.config.rawBuffer is true and a message is received. |
  316. | **_your event type_** | **_your event data_** | triggered when a JSON message is received. The event name will be the type string from your message and the param will be the data object from your message eg : `{ type:'myEvent',data:{a:1}}` |
  317. ### Multiple IPC Instances
  318. Sometimes you might need explicit and independent instances of @achrinza/node-ipc. Just for such scenarios we have exposed the core IPC class on the IPC singleton.
  319. ```javascript
  320. const RawIPC = require("@achrinza/node-ipc").IPC;
  321. const ipc = new RawIPC();
  322. const someOtherExplicitIPC = new RawIPC();
  323. //OR
  324. const ipc = require("@achrinza/node-ipc");
  325. const someOtherExplicitIPC = new ipc.IPC();
  326. //setting explicit configs
  327. //keep one silent and the other verbose
  328. ipc.config.silent = true;
  329. someOtherExplicitIPC.config.silent = true;
  330. //make one a raw binary and the other json based ipc
  331. ipc.config.rawBuffer = false;
  332. someOtherExplicitIPC.config.rawBuffer = true;
  333. someOtherExplicitIPC.config.encoding = "hex";
  334. ```
  335. ---
  336. ### Basic Examples
  337. You can find [Advanced Examples](https://github.com/RIAEvangelist/@achrinza/node-ipc/tree/master/example) in the examples folder. In the examples you will find more complex demos including multi client examples.
  338. #### Server for Unix Sockets, Windows Sockets & TCP Sockets
  339. The server is the process keeping a socket for IPC open. Multiple sockets can connect to this server and talk to it. It can also broadcast to all clients or emit to a specific client. This is the most basic example which will work for local Unix and Windows Sockets as well as local or remote network TCP Sockets.
  340. ```javascript
  341. var ipc = require("@achrinza/node-ipc");
  342. ipc.config.id = "world";
  343. ipc.config.retry = 1500;
  344. ipc.serve(function () {
  345. ipc.server.on("message", function (data, socket) {
  346. ipc.log("got a message : ".debug, data);
  347. ipc.server.emit(
  348. socket,
  349. "message", //this can be anything you want so long as
  350. //your client knows.
  351. data + " world!"
  352. );
  353. });
  354. ipc.server.on("socket.disconnected", function (socket, destroyedSocketID) {
  355. ipc.log("client " + destroyedSocketID + " has disconnected!");
  356. });
  357. });
  358. ipc.server.start();
  359. ```
  360. #### Client for Unix Sockets & TCP Sockets
  361. The client connects to the servers socket for Inter Process Communication. The socket will receive events emitted to it specifically as well as events which are broadcast out on the socket by the server. This is the most basic example which will work for both local Unix Sockets and local or remote network TCP Sockets.
  362. ```javascript
  363. var ipc = require("@achrinza/node-ipc");
  364. ipc.config.id = "hello";
  365. ipc.config.retry = 1500;
  366. ipc.connectTo("world", function () {
  367. ipc.of.world.on("connect", function () {
  368. ipc.log("## connected to world ##".rainbow, ipc.config.delay);
  369. ipc.of.world.emit(
  370. "message", //any event or message type your server listens for
  371. "hello"
  372. );
  373. });
  374. ipc.of.world.on("disconnect", function () {
  375. ipc.log("disconnected from world".notice);
  376. });
  377. ipc.of.world.on(
  378. "message", //any event or message type your server listens for
  379. function (data) {
  380. ipc.log("got a message from world : ".debug, data);
  381. }
  382. );
  383. });
  384. ```
  385. #### Server & Client for UDP Sockets
  386. UDP Sockets are different than Unix, Windows & TCP Sockets because they must be bound to a unique port on their machine to receive messages. For example, A TCP, Unix, or Windows Socket client could just connect to a separate TCP, Unix, or Windows Socket sever. That client could then exchange, both send and receive, data on the servers port or location. UDP Sockets can not do this. They must bind to a port to receive or send data.
  387. This means a UDP Client and Server are the same thing because in order to receive data, a UDP Socket must have its own port to receive data on, and only one process can use this port at a time. It also means that in order to `emit` or `broadcast` data the UDP server will need to know the host and port of the Socket it intends to broadcast the data to.
  388. This is the most basic example which will work for both local and remote UDP Sockets.
  389. ##### UDP Server 1 - "World"
  390. ```javascript
  391. var ipc = require("../../../@achrinza/node-ipc");
  392. ipc.config.id = "world";
  393. ipc.config.retry = 1500;
  394. ipc.serveNet("udp4", function () {
  395. console.log(123);
  396. ipc.server.on("message", function (data, socket) {
  397. ipc.log(
  398. "got a message from ".debug,
  399. data.from.variable,
  400. " : ".debug,
  401. data.message.variable
  402. );
  403. ipc.server.emit(socket, "message", {
  404. from: ipc.config.id,
  405. message: data.message + " world!",
  406. });
  407. });
  408. console.log(ipc.server);
  409. });
  410. ipc.server.start();
  411. ```
  412. ##### UDP Server 2 - "Hello"
  413. _note_ we set the port here to 8001 because the world server is already using the default ipc.config.networkPort of 8000. So we can not bind to 8000 while world is using it.
  414. ```javascript
  415. ipc.config.id = "hello";
  416. ipc.config.retry = 1500;
  417. ipc.serveNet(8001, "udp4", function () {
  418. ipc.server.on("message", function (data) {
  419. ipc.log("got Data");
  420. ipc.log(
  421. "got a message from ".debug,
  422. data.from.variable,
  423. " : ".debug,
  424. data.message.variable
  425. );
  426. });
  427. ipc.server.emit(
  428. {
  429. address: "127.0.0.1", //any hostname will work
  430. port: ipc.config.networkPort,
  431. },
  432. "message",
  433. {
  434. from: ipc.config.id,
  435. message: "Hello",
  436. }
  437. );
  438. });
  439. ipc.server.start();
  440. ```
  441. #### Raw Buffer or Binary Sockets
  442. Binary or Buffer sockets can be used with any of the above socket types, however the way data events are emit is **_slightly_** different. These may come in handy if working with embedded systems or C / C++ processes. You can even make sure to match C or C++ string typing.
  443. When setting up a rawBuffer socket you must specify it as such :
  444. ```javascript
  445. ipc.config.rawBuffer = true;
  446. ```
  447. You can also specify its encoding type. The default is `utf8`
  448. ```javascript
  449. ipc.config.encoding = "utf8";
  450. ```
  451. emit string buffer :
  452. ```javascript
  453. //server
  454. ipc.server.emit(socket, "hello");
  455. //client
  456. ipc.of.world.emit("hello");
  457. ```
  458. emit byte array buffer :
  459. ```javascript
  460. //hex encoding may work best for this.
  461. ipc.config.encoding = "hex";
  462. //server
  463. ipc.server.emit(socket, [10, 20, 30]);
  464. //client
  465. ipc.server.emit([10, 20, 30]);
  466. ```
  467. emit binary or hex array buffer, this is best for real time data transfer, especially whan connecting to C or C++ processes, or embedded systems :
  468. ```javascript
  469. ipc.config.encoding = "hex";
  470. //server
  471. ipc.server.emit(socket, [0x05, 0x6d, 0x5c]);
  472. //client
  473. ipc.server.emit([0x05, 0x6d, 0x5c]);
  474. ```
  475. Writing explicit buffers, int types, doubles, floats etc. as well as big endian and little endian data to raw buffer nostly valuable when connecting to C or C++ processes, or embedded systems (see more detailed info on buffers as well as UInt, Int, double etc. here)[https://nodejs.org/api/buffer.html]:
  476. ```javascript
  477. ipc.config.encoding = "hex";
  478. //make a 6 byte buffer for example
  479. const myBuffer = Buffer.alloc(6).fill(0);
  480. //fill the first 2 bytes with a 16 bit (2 byte) short unsigned int
  481. //write a UInt16 (2 byte or short) as Big Endian
  482. myBuffer.writeUInt16BE(
  483. 2, //value to write
  484. 0 //offset in bytes
  485. );
  486. //OR
  487. myBuffer.writeUInt16LE(0x2, 0);
  488. //OR
  489. myBuffer.writeUInt16LE(0x02, 0);
  490. //fill the remaining 4 bytes with a 32 bit (4 byte) long unsigned int
  491. //write a UInt32 (4 byte or long) as Big Endian
  492. myBuffer.writeUInt32BE(
  493. 16772812, //value to write
  494. 2 //offset in bytes
  495. );
  496. //OR
  497. myBuffer.writeUInt32BE(0xffeecc, 0);
  498. //server
  499. ipc.server.emit(socket, myBuffer);
  500. //client
  501. ipc.server.emit(myBuffer);
  502. ```
  503. #### Server with the `cluster` Module
  504. `@achrinza/node-ipc` can be used with Node.js' [cluster module](https://nodejs.org/api/cluster.html) to provide the ability to have multiple readers for a single socket. Doing so simply requires you to set the `unlink` property in the config to `false` and take care of unlinking the socket path in the master process:
  505. ##### Server
  506. ```javascript
  507. const fs = require("fs");
  508. const ipc = require("../../../@achrinza/node-ipc");
  509. const cpuCount = require("os").cpus().length;
  510. const cluster = require("cluster");
  511. const socketPath = "/tmp/ipc.sock";
  512. ipc.config.unlink = false;
  513. if (cluster.isMaster) {
  514. if (fs.existsSync(socketPath)) {
  515. fs.unlinkSync(socketPath);
  516. }
  517. for (let i = 0; i < cpuCount; i++) {
  518. cluster.fork();
  519. }
  520. } else {
  521. ipc.serve(socketPath, function () {
  522. ipc.server.on("currentDate", function (data, socket) {
  523. console.log(`pid ${process.pid} got: `, data);
  524. });
  525. });
  526. ipc.server.start();
  527. console.log(`pid ${process.pid} listening on ${socketPath}`);
  528. }
  529. ```
  530. ##### Client
  531. ```javascript
  532. const fs = require("fs");
  533. const ipc = require("../../@achrinza/node-ipc");
  534. const socketPath = "/tmp/ipc.sock";
  535. //loop forever so you can see the pid of the cluster sever change in the logs
  536. setInterval(function () {
  537. ipc.connectTo("world", socketPath, connecting);
  538. }, 2000);
  539. function connecting(socket) {
  540. ipc.of.world.on("connect", function () {
  541. ipc.of.world.emit("currentDate", {
  542. message: new Date().toISOString(),
  543. });
  544. ipc.disconnect("world");
  545. });
  546. }
  547. ```
  548. #### Licensed under MIT license
  549. See the [MIT license](https://github.com/RIAEvangelist/@achrinza/node-ipc/blob/master/license) file.