PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/src/org/zeromq/ZMQ.java

https://github.com/nieksand/jzmq
Java | 1414 lines | 498 code | 169 blank | 747 comment | 53 complexity | bc4cfc7479b4c9f1dc186a8973619020 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-3.0, BSD-3-Clause-No-Nuclear-License-2014
  1. /*
  2. Copyright (c) 2007-2010 iMatix Corporation
  3. This file is part of 0MQ.
  4. 0MQ is free software; you can redistribute it and/or modify it under
  5. the terms of the Lesser GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. 0MQ is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. Lesser GNU General Public License for more details.
  12. You should have received a copy of the Lesser GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package org.zeromq;
  16. import java.util.LinkedList;
  17. /**
  18. * ZeroMQ JNI Bindings.
  19. *
  20. * @author Gonzalo Diethelm
  21. *
  22. */
  23. public class ZMQ {
  24. static {
  25. // if no embedded native library, revert to loading from java.library.path
  26. if (!EmbeddedLibraryTools.LOADED_EMBEDDED_LIBRARY)
  27. System.loadLibrary ("jzmq");
  28. }
  29. // Values for flags in Socket's send and recv functions.
  30. /**
  31. * Socket flag to indicate a nonblocking send or recv mode.
  32. */
  33. public static final int NOBLOCK = 1;
  34. public static final int DONTWAIT = 1;
  35. /**
  36. * Socket flag to indicate that more message parts are coming.
  37. */
  38. public static final int SNDMORE = 2;
  39. // Socket types, used when creating a Socket.
  40. /**
  41. * Flag to specify a exclusive pair of sockets.
  42. */
  43. public static final int PAIR = 0;
  44. /**
  45. * Flag to specify a PUB socket, receiving side must be a SUB or XSUB.
  46. */
  47. public static final int PUB = 1;
  48. /**
  49. * Flag to specify the receiving part of the PUB or XPUB socket.
  50. */
  51. public static final int SUB = 2;
  52. /**
  53. * Flag to specify a REQ socket, receiving side must be a REP.
  54. */
  55. public static final int REQ = 3;
  56. /**
  57. * Flag to specify the receiving part of a REQ socket.
  58. */
  59. public static final int REP = 4;
  60. /**
  61. * Flag to specify a DEALER socket (aka XREQ).
  62. * DEALER is really a combined ventilator / sink
  63. * that does load-balancing on output and fair-queuing on input
  64. * with no other semantics. It is the only socket type that lets
  65. * you shuffle messages out to N nodes and shuffle the replies
  66. * back, in a raw bidirectional asynch pattern.
  67. */
  68. public static final int DEALER = 5;
  69. /**
  70. * Old alias for DEALER flag.
  71. * Flag to specify a XREQ socket, receiving side must be a XREP.
  72. *
  73. * @deprecated As of release 3.0 of zeromq, replaced by {@link #DEALER}
  74. */
  75. public static final int XREQ = DEALER;
  76. /**
  77. * Flag to specify ROUTER socket (aka XREP).
  78. * ROUTER is the socket that creates and consumes request-reply
  79. * routing envelopes. It is the only socket type that lets you route
  80. * messages to specific connections if you know their identities.
  81. */
  82. public static final int ROUTER = 6;
  83. /**
  84. * Old alias for ROUTER flag.
  85. * Flag to specify the receiving part of a XREQ socket.
  86. *
  87. * @deprecated As of release 3.0 of zeromq, replaced by {@link #ROUTER}
  88. */
  89. public static final int XREP = ROUTER;
  90. /**
  91. * Flag to specify the receiving part of a PUSH socket.
  92. */
  93. public static final int PULL = 7;
  94. /**
  95. * Flag to specify a PUSH socket, receiving side must be a PULL.
  96. */
  97. public static final int PUSH = 8;
  98. /**
  99. * Flag to specify a XPUB socket, receiving side must be a SUB or XSUB.
  100. * Subscriptions can be received as a message. Subscriptions start with
  101. * a '1' byte. Unsubscriptions start with a '0' byte.
  102. */
  103. public static final int XPUB = 9;
  104. /**
  105. * Flag to specify the receiving part of the PUB or XPUB socket. Allows
  106. */
  107. public static final int XSUB = 10;
  108. /**
  109. * Flag to specify a STREAMER device.
  110. */
  111. public static final int STREAMER = 1;
  112. /**
  113. * Flag to specify a FORWARDER device.
  114. */
  115. public static final int FORWARDER = 2;
  116. /**
  117. * Flag to specify a QUEUE device.
  118. */
  119. public static final int QUEUE = 3;
  120. /**
  121. * @see ZMQ#PULL
  122. */
  123. @Deprecated
  124. public static final int UPSTREAM = PULL;
  125. /**
  126. * @see ZMQ#PUSH
  127. */
  128. @Deprecated
  129. public static final int DOWNSTREAM = PUSH;
  130. /**
  131. * @return Major version number of the ZMQ library.
  132. */
  133. public static int getMajorVersion ()
  134. {
  135. return version_major ();
  136. }
  137. /**
  138. * @return Major version number of the ZMQ library.
  139. */
  140. public static int getMinorVersion ()
  141. {
  142. return version_minor ();
  143. }
  144. /**
  145. * @return Major version number of the ZMQ library.
  146. */
  147. public static int getPatchVersion ()
  148. {
  149. return version_patch ();
  150. }
  151. /**
  152. * @return Full version number of the ZMQ library used for comparing versions.
  153. */
  154. public static int getFullVersion ()
  155. {
  156. return version_full ();
  157. }
  158. /**
  159. * @param major Version major component.
  160. * @param minor Version minor component.
  161. * @param patch Version patch component.
  162. *
  163. * @return Comparible single int version number.
  164. */
  165. public static int makeVersion ( final int major,
  166. final int minor,
  167. final int patch )
  168. {
  169. return make_version ( major, minor, patch );
  170. }
  171. /**
  172. * @return String version number in the form major.minor.patch.
  173. */
  174. public static String getVersionString ()
  175. {
  176. return String.format ( "%d.%d.%d",
  177. version_major (),
  178. version_minor (),
  179. version_patch () );
  180. }
  181. protected static native int version_full();
  182. protected static native int version_major();
  183. protected static native int version_minor();
  184. protected static native int version_patch();
  185. protected static native int make_version(int major, int minor, int patch);
  186. protected static native long ENOTSUP();
  187. protected static native long EPROTONOSUPPORT();
  188. protected static native long ENOBUFS();
  189. protected static native long ENETDOWN();
  190. protected static native long EADDRINUSE();
  191. protected static native long EADDRNOTAVAIL();
  192. protected static native long ECONNREFUSED();
  193. protected static native long EINPROGRESS();
  194. protected static native long EMTHREAD();
  195. protected static native long EFSM();
  196. protected static native long ENOCOMPATPROTO();
  197. protected static native long ETERM();
  198. /**
  199. * Inner class: Error.
  200. */
  201. public enum Error {
  202. ENOTSUP(ENOTSUP()),
  203. EPROTONOSUPPORT(EPROTONOSUPPORT()),
  204. ENOBUFS(ENOBUFS()),
  205. ENETDOWN(ENETDOWN()),
  206. EADDRINUSE(EADDRINUSE()),
  207. EADDRNOTAVAIL(EADDRNOTAVAIL()),
  208. ECONNREFUSED(ECONNREFUSED()),
  209. EINPROGRESS(EINPROGRESS()),
  210. EMTHREAD(EMTHREAD()),
  211. EFSM(EFSM()),
  212. ENOCOMPATPROTO(ENOCOMPATPROTO()),
  213. ETERM(ETERM());
  214. private final long code;
  215. Error(long code) {
  216. this.code = code;
  217. }
  218. public long getCode() {
  219. return code;
  220. }
  221. public static Error findByCode(int code) {
  222. for (Error e : Error.class.getEnumConstants()) {
  223. if (e.getCode() == code) {
  224. return e;
  225. }
  226. }
  227. throw new IllegalArgumentException("Unknown " + Error.class.getName() + " enum code:" + code);
  228. }
  229. }
  230. /**
  231. * Create a new Context.
  232. *
  233. * @param ioThreads
  234. * Number of threads to use, usually 1 is sufficient for most use cases.
  235. * @return the Context
  236. */
  237. public static Context context (int ioThreads) {
  238. return new Context (ioThreads);
  239. }
  240. /**
  241. * Inner class: Context.
  242. */
  243. public static class Context {
  244. /**
  245. * This is an explicit "destructor". It can be called to ensure the corresponding 0MQ
  246. * Context has been disposed of.
  247. */
  248. public void term () {
  249. finalize ();
  250. }
  251. /**
  252. * Create a new Socket within this context.
  253. *
  254. * @param type
  255. * the socket type.
  256. * @return the newly created Socket.
  257. */
  258. public Socket socket (int type) {
  259. return new Socket (this, type);
  260. }
  261. /**
  262. * Create a new Poller within this context, with a default size.
  263. *
  264. * @return the newly created Poller.
  265. */
  266. public Poller poller () {
  267. return new Poller (this);
  268. }
  269. /**
  270. * Create a new Poller within this context, with a specified initial size.
  271. *
  272. * @param size
  273. * the poller initial size.
  274. * @return the newly created Poller.
  275. */
  276. public Poller poller (int size) {
  277. return new Poller (this, size);
  278. }
  279. /**
  280. * Class constructor.
  281. *
  282. * @param ioThreads
  283. * size of the threads pool to handle I/O operations.
  284. */
  285. protected Context (int ioThreads) {
  286. construct (ioThreads);
  287. }
  288. /** Initialize the JNI interface */
  289. protected native void construct (int ioThreads);
  290. /** Free all resources used by JNI interface. */
  291. @Override
  292. protected native void finalize ();
  293. /**
  294. * Get the underlying context handle. This is private because it is only accessed from JNI,
  295. * where Java access controls are ignored.
  296. *
  297. * @return the internal 0MQ context handle.
  298. */
  299. private long getContextHandle () {
  300. return this.contextHandle;
  301. }
  302. /** Opaque data used by JNI driver. */
  303. private long contextHandle;
  304. }
  305. /**
  306. * Inner class: Socket.
  307. */
  308. public static class Socket {
  309. /**
  310. * This is an explicit "destructor". It can be called to ensure the corresponding 0MQ Socket
  311. * has been disposed of.
  312. */
  313. public void close () {
  314. finalize ();
  315. }
  316. /**
  317. * The 'ZMQ_TYPE option shall retrieve the socket type for the specified
  318. * 'socket'. The socket type is specified at socket creation time and
  319. * cannot be modified afterwards.
  320. *
  321. * @return the socket type.
  322. * @since 2.1.0
  323. */
  324. public int getType () {
  325. if (ZMQ.version_full() < ZMQ.make_version(2, 1, 0))
  326. return -1;
  327. return (int) getLongSockopt (TYPE);
  328. }
  329. /**
  330. * @see #setLinger(long)
  331. *
  332. * @return the linger period.
  333. * @since 2.1.0
  334. */
  335. public long getLinger () {
  336. if (ZMQ.version_full() < ZMQ.make_version(2, 1, 0))
  337. return -1;
  338. return getLongSockopt (LINGER);
  339. }
  340. /**
  341. * @see #setReconnectIVL(long)
  342. *
  343. * @return the reconnectIVL.
  344. * @since 3.0.0
  345. */
  346. public long getReconnectIVL () {
  347. if (ZMQ.version_full() < ZMQ.make_version(2, 1, 10))
  348. return -1;
  349. return getLongSockopt (RECONNECT_IVL);
  350. }
  351. /**
  352. * @see #setBacklog(long)
  353. *
  354. * @return the backlog.
  355. * @since 3.0.0
  356. */
  357. public long getBacklog () {
  358. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  359. return -1;
  360. return getLongSockopt (BACKLOG);
  361. }
  362. /**
  363. * @see #setReconnectIVLMax(long)
  364. *
  365. * @return the reconnectIVLMax.
  366. * @since 3.0.0
  367. */
  368. public long getReconnectIVLMax () {
  369. if (ZMQ.version_full() < ZMQ.make_version(2, 1, 10))
  370. return -1;
  371. return getLongSockopt (RECONNECT_IVL_MAX);
  372. }
  373. /**
  374. * @see #setMaxMsgSize(long)
  375. *
  376. * @return the maxMsgSize.
  377. * @since 3.0.0
  378. */
  379. public long getMaxMsgSize () {
  380. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  381. return -1;
  382. return getLongSockopt (MAXMSGSIZE);
  383. }
  384. /**
  385. * @see #setSndHWM(long)
  386. *
  387. * @return the SndHWM.
  388. * @since 3.0.0
  389. */
  390. public long getSndHWM () {
  391. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  392. return -1;
  393. return getLongSockopt (SNDHWM);
  394. }
  395. /**
  396. * @see #setRcvHWM(long)
  397. *
  398. * @return the recvHWM period.
  399. * @since 3.0.0
  400. */
  401. public long getRcvHWM () {
  402. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  403. return -1;
  404. return getLongSockopt (RCVHWM);
  405. }
  406. /**
  407. * @see #setHWM(long)
  408. *
  409. * @return the High Water Mark.
  410. */
  411. public long getHWM () {
  412. if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0))
  413. return -1;
  414. return getLongSockopt (HWM);
  415. }
  416. /**
  417. * @see #setSwap(long)
  418. *
  419. * @return the number of messages to swap at most.
  420. */
  421. public long getSwap () {
  422. if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0))
  423. return -1;
  424. return getLongSockopt (SWAP);
  425. }
  426. /**
  427. * @see #setAffinity(long)
  428. *
  429. * @return the affinity.
  430. */
  431. public long getAffinity () {
  432. return getLongSockopt (AFFINITY);
  433. }
  434. /**
  435. * @see #setIdentity(byte[])
  436. *
  437. * @return the Identitiy.
  438. */
  439. public byte [] getIdentity () {
  440. return getBytesSockopt (IDENTITY);
  441. }
  442. /**
  443. * @see #setRate(long)
  444. *
  445. * @return the Rate.
  446. */
  447. public long getRate () {
  448. return getLongSockopt (RATE);
  449. }
  450. /**
  451. * @see #setRecoveryInterval(long)
  452. *
  453. * @return the RecoveryIntervall.
  454. */
  455. public long getRecoveryInterval () {
  456. return getLongSockopt (RECOVERY_IVL);
  457. }
  458. /**
  459. * @see #setMulticastLoop(boolean)
  460. *
  461. * @return the Multicast Loop.
  462. */
  463. public boolean hasMulticastLoop () {
  464. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  465. return false;
  466. return getLongSockopt (MCAST_LOOP) != 0;
  467. }
  468. /**
  469. * Sets the time-to-live field in every multicast packet sent from this socket.
  470. * The default is 1 which means that the multicast packets don't leave the local
  471. * network.
  472. *
  473. * @param mcast_hops
  474. */
  475. public void setMulticastHops (long mcast_hops) {
  476. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  477. return;
  478. setLongSockopt (MULTICAST_HOPS, mcast_hops);
  479. }
  480. /**
  481. * @see #setMulticastHops(long)
  482. *
  483. * @return the Multicast Hops.
  484. */
  485. public long getMulticastHops () {
  486. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  487. return 1;
  488. return getLongSockopt (MULTICAST_HOPS);
  489. }
  490. /**
  491. * Sets the timeout for receive operation on the socket. If the value is 0, recv
  492. * will return immediately, with a EAGAIN error if there is no message to receive.
  493. * If the value is -1, it will block until a message is available. For all other
  494. * values, it will wait for a message for that amount of time before returning with
  495. * an EAGAIN error.
  496. *
  497. * @param timeout
  498. */
  499. public void setReceiveTimeOut (long timeout) {
  500. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  501. return;
  502. setLongSockopt (RCVTIMEO, timeout);
  503. }
  504. /**
  505. * @see #setReceiveTimeOut(long)
  506. *
  507. * @return the Receive Timeout
  508. */
  509. public long getReceiveTimeOut () {
  510. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  511. return -1;
  512. return getLongSockopt (RCVTIMEO);
  513. }
  514. /**
  515. * Sets the timeout for send operation on the socket. If the value is 0, send
  516. * will return immediately, with a EAGAIN error if the message cannot be sent.
  517. * If the value is -1, it will block until the message is sent. For all other
  518. * values, it will try to send the message for that amount of time before
  519. * returning with an EAGAIN error.
  520. *
  521. * @param timeout
  522. */
  523. public void setSendTimeOut (long timeout) {
  524. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  525. return;
  526. setLongSockopt (SNDTIMEO, timeout);
  527. }
  528. /**
  529. * @see #setSendTimeOut(long)
  530. *
  531. * @return the Send Timeout.
  532. */
  533. public long getSendTimeOut () {
  534. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  535. return -1;
  536. return getLongSockopt (SNDTIMEO);
  537. }
  538. /**
  539. * @see #setSendBufferSize(long)
  540. *
  541. * @return the kernel send buffer size.
  542. */
  543. public long getSendBufferSize () {
  544. return getLongSockopt (SNDBUF);
  545. }
  546. /**
  547. * @see #setReceiveBufferSize(long)
  548. *
  549. * @return the kernel receive buffer size.
  550. */
  551. public long getReceiveBufferSize () {
  552. return getLongSockopt (RCVBUF);
  553. }
  554. /**
  555. * The 'ZMQ_RCVMORE' option shall return a boolean value indicating if the multi-part
  556. * message currently being read from the specified 'socket' has more message parts to
  557. * follow. If there are no message parts to follow or if the message currently being read is
  558. * not a multi-part message a value of zero shall be returned. Otherwise, a value of 1 shall
  559. * be returned.
  560. *
  561. * @return true if there are more messages to receive.
  562. */
  563. public boolean hasReceiveMore () {
  564. return getLongSockopt (RCVMORE) != 0;
  565. }
  566. /**
  567. * The 'ZMQ_FD' option shall retrieve file descriptor associated with the 0MQ
  568. * socket. The descriptor can be used to integrate 0MQ socket into an existing
  569. * event loop. It should never be used for anything else than polling -- such as
  570. * reading or writing. The descriptor signals edge-triggered IN event when
  571. * something has happened within the 0MQ socket. It does not necessarily mean that
  572. * the messages can be read or written. Check ZMQ_EVENTS option to find out whether
  573. * the 0MQ socket is readable or writeable.
  574. *
  575. * @return the underlying file descriptor.
  576. * @since 2.1.0
  577. */
  578. public long getFD () {
  579. if (ZMQ.version_full() < ZMQ.make_version(2, 1, 0))
  580. return -1;
  581. return getLongSockopt (FD);
  582. }
  583. /**
  584. * The 'ZMQ_EVENTS' option shall retrieve event flags for the specified socket.
  585. * If a message can be read from the socket ZMQ_POLLIN flag is set. If message can
  586. * be written to the socket ZMQ_POLLOUT flag is set.
  587. *
  588. * @return the mask of outstanding events.
  589. * @since 2.1.0
  590. */
  591. public long getEvents () {
  592. if (ZMQ.version_full() < ZMQ.make_version(2, 1, 0))
  593. return -1;
  594. return getLongSockopt (EVENTS);
  595. }
  596. /**
  597. * The 'ZMQ_LINGER' option shall retrieve the period for pending outbound
  598. * messages to linger in memory after closing the socket. Value of -1 means
  599. * infinite. Pending messages will be kept until they are fully transferred to
  600. * the peer. Value of 0 means that all the pending messages are dropped immediately
  601. * when socket is closed. Positive value means number of milliseconds to keep
  602. * trying to send the pending messages before discarding them.
  603. *
  604. * @param linger
  605. * the linger period.
  606. * @since 2.1.0
  607. */
  608. public void setLinger (long linger) {
  609. if (ZMQ.version_full() < ZMQ.make_version(2, 1, 0))
  610. return;
  611. setLongSockopt (LINGER, linger);
  612. }
  613. /**
  614. * @since 3.0.0
  615. */
  616. public void setReconnectIVL (long reconnectIVL) {
  617. if (ZMQ.version_full() < ZMQ.make_version(2, 1, 10))
  618. return;
  619. setLongSockopt (RECONNECT_IVL, reconnectIVL);
  620. }
  621. /**
  622. * @since 3.0.0
  623. */
  624. public void setBacklog (long backlog) {
  625. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  626. return;
  627. setLongSockopt (BACKLOG, backlog);
  628. }
  629. /**
  630. * @since 3.0.0
  631. */
  632. public void setReconnectIVLMax (long reconnectIVLMax) {
  633. if (ZMQ.version_full() < ZMQ.make_version(2, 1, 10))
  634. return;
  635. setLongSockopt (RECONNECT_IVL_MAX, reconnectIVLMax);
  636. }
  637. /**
  638. * @since 3.0.0
  639. */
  640. public void setMaxMsgSize (long maxMsgSize) {
  641. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  642. return;
  643. setLongSockopt (MAXMSGSIZE, maxMsgSize);
  644. }
  645. /**
  646. * @since 3.0.0
  647. */
  648. public void setSndHWM (long sndHWM) {
  649. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  650. return;
  651. setLongSockopt (SNDHWM, sndHWM);
  652. }
  653. /**
  654. * @since 3.0.0
  655. */
  656. public void setRcvHWM (long rcvHWM) {
  657. if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0))
  658. return;
  659. setLongSockopt (RCVHWM, rcvHWM);
  660. }
  661. /**
  662. * The 'ZMQ_HWM' option shall set the high water mark for the specified 'socket'. The high
  663. * water mark is a hard limit on the maximum number of outstanding messages 0MQ shall queue
  664. * in memory for any single peer that the specified 'socket' is communicating with.
  665. *
  666. * If this limit has been reached the socket shall enter an exceptional state and depending
  667. * on the socket type, 0MQ shall take appropriate action such as blocking or dropping sent
  668. * messages. Refer to the individual socket descriptions in the man page of zmq_socket[3] for
  669. * details on the exact action taken for each socket type.
  670. *
  671. * @param hwm
  672. * the number of messages to queue.
  673. */
  674. public void setHWM (long hwm) {
  675. if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0))
  676. return;
  677. setLongSockopt (HWM, hwm);
  678. }
  679. /**
  680. * Get the Swap. The 'ZMQ_SWAP' option shall set the disk offload (swap) size for the
  681. * specified 'socket'. A socket which has 'ZMQ_SWAP' set to a non-zero value may exceed its
  682. * high water mark; in this case outstanding messages shall be offloaded to storage on disk
  683. * rather than held in memory.
  684. *
  685. * @param swap
  686. * The value of 'ZMQ_SWAP' defines the maximum size of the swap space in bytes.
  687. */
  688. public void setSwap (long swap) {
  689. if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0))
  690. return;
  691. setLongSockopt (SWAP, swap);
  692. }
  693. /**
  694. * Get the Affinity. The 'ZMQ_AFFINITY' option shall set the I/O thread affinity for newly
  695. * created connections on the specified 'socket'.
  696. *
  697. * Affinity determines which threads from the 0MQ I/O thread pool associated with the
  698. * socket's _context_ shall handle newly created connections. A value of zero specifies no
  699. * affinity, meaning that work shall be distributed fairly among all 0MQ I/O threads in the
  700. * thread pool. For non-zero values, the lowest bit corresponds to thread 1, second lowest
  701. * bit to thread 2 and so on. For example, a value of 3 specifies that subsequent
  702. * connections on 'socket' shall be handled exclusively by I/O threads 1 and 2.
  703. *
  704. * See also in the man page of zmq_init[3] for details on allocating the number of I/O threads for a
  705. * specific _context_.
  706. *
  707. * @param affinity
  708. * the affinity.
  709. */
  710. public void setAffinity (long affinity) {
  711. setLongSockopt (AFFINITY, affinity);
  712. }
  713. /**
  714. * The 'ZMQ_IDENTITY' option shall set the identity of the specified 'socket'. Socket
  715. * identity determines if existing 0MQ infastructure (_message queues_, _forwarding
  716. * devices_) shall be identified with a specific application and persist across multiple
  717. * runs of the application.
  718. *
  719. * If the socket has no identity, each run of an application is completely separate from
  720. * other runs. However, with identity set the socket shall re-use any existing 0MQ
  721. * infrastructure configured by the previous run(s). Thus the application may receive
  722. * messages that were sent in the meantime, _message queue_ limits shall be shared with
  723. * previous run(s) and so on.
  724. *
  725. * Identity should be at least one byte and at most 255 bytes long. Identities starting with
  726. * binary zero are reserved for use by 0MQ infrastructure.
  727. *
  728. * @param identity
  729. */
  730. public void setIdentity (byte [] identity) {
  731. setBytesSockopt (IDENTITY, identity);
  732. }
  733. /**
  734. * The 'ZMQ_SUBSCRIBE' option shall establish a new message filter on a 'ZMQ_SUB' socket.
  735. * Newly created 'ZMQ_SUB' sockets shall filter out all incoming messages, therefore you
  736. * should call this option to establish an initial message filter.
  737. *
  738. * An empty 'option_value' of length zero shall subscribe to all incoming messages. A
  739. * non-empty 'option_value' shall subscribe to all messages beginning with the specified
  740. * prefix. Mutiple filters may be attached to a single 'ZMQ_SUB' socket, in which case a
  741. * message shall be accepted if it matches at least one filter.
  742. *
  743. * @param topic
  744. */
  745. public void subscribe (byte [] topic) {
  746. setBytesSockopt (SUBSCRIBE, topic);
  747. }
  748. /**
  749. * The 'ZMQ_UNSUBSCRIBE' option shall remove an existing message filter on a 'ZMQ_SUB'
  750. * socket. The filter specified must match an existing filter previously established with
  751. * the 'ZMQ_SUBSCRIBE' option. If the socket has several instances of the same filter
  752. * attached the 'ZMQ_UNSUBSCRIBE' option shall remove only one instance, leaving the rest in
  753. * place and functional.
  754. *
  755. * @param topic
  756. */
  757. public void unsubscribe (byte [] topic) {
  758. setBytesSockopt (UNSUBSCRIBE, topic);
  759. }
  760. /**
  761. * The 'ZMQ_RATE' option shall set the maximum send or receive data rate for multicast
  762. * transports such as in the man page of zmq_pgm[7] using the specified 'socket'.
  763. *
  764. * @param rate
  765. */
  766. public void setRate (long rate) {
  767. setLongSockopt (RATE, rate);
  768. }
  769. /**
  770. * The 'ZMQ_RECOVERY_IVL' option shall set the recovery interval for multicast transports
  771. * using the specified 'socket'. The recovery interval determines the maximum time in
  772. * seconds that a receiver can be absent from a multicast group before unrecoverable data
  773. * loss will occur.
  774. *
  775. * CAUTION: Excersize care when setting large recovery intervals as the data needed for
  776. * recovery will be held in memory. For example, a 1 minute recovery interval at a data rate
  777. * of 1Gbps requires a 7GB in-memory buffer. {Purpose of this Method}
  778. *
  779. * @param recovery_ivl
  780. */
  781. public void setRecoveryInterval (long recovery_ivl) {
  782. setLongSockopt (RECOVERY_IVL, recovery_ivl);
  783. }
  784. /**
  785. * The 'ZMQ_MCAST_LOOP' option shall control whether data sent via multicast transports
  786. * using the specified 'socket' can also be received by the sending host via loopback. A
  787. * value of zero disables the loopback functionality, while the default value of 1 enables
  788. * the loopback functionality. Leaving multicast loopback enabled when it is not required
  789. * can have a negative impact on performance. Where possible, disable 'ZMQ_MCAST_LOOP' in
  790. * production environments.
  791. *
  792. * @param mcast_loop
  793. */
  794. public void setMulticastLoop (boolean mcast_loop) {
  795. if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0))
  796. return;
  797. setLongSockopt (MCAST_LOOP, mcast_loop ? 1 : 0);
  798. }
  799. /**
  800. * The 'ZMQ_SNDBUF' option shall set the underlying kernel transmit buffer size for the
  801. * 'socket' to the specified size in bytes. A value of zero means leave the OS default
  802. * unchanged. For details please refer to your operating system documentation for the
  803. * 'SO_SNDBUF' socket option.
  804. *
  805. * @param sndbuf
  806. */
  807. public void setSendBufferSize (long sndbuf) {
  808. setLongSockopt (SNDBUF, sndbuf);
  809. }
  810. /**
  811. * The 'ZMQ_RCVBUF' option shall set the underlying kernel receive buffer size for the
  812. * 'socket' to the specified size in bytes. A value of zero means leave the OS default
  813. * unchanged. For details refer to your operating system documentation for the 'SO_RCVBUF'
  814. * socket option.
  815. *
  816. * @param rcvbuf
  817. */
  818. public void setReceiveBufferSize (long rcvbuf) {
  819. setLongSockopt (RCVBUF, rcvbuf);
  820. }
  821. /**
  822. * Bind to network interface. Start listening for new connections.
  823. *
  824. * @param addr
  825. * the endpoint to bind to.
  826. */
  827. public native void bind (String addr);
  828. /**
  829. * Connect to remote application.
  830. *
  831. * @param addr
  832. * the endpoint to connect to.
  833. */
  834. public native void connect (String addr);
  835. /**
  836. * Send a message.
  837. *
  838. * @param msg
  839. * the message to send, as an array of bytes.
  840. * @param flags
  841. * the flags to apply to the send operation.
  842. * @return true if send was successful, false otherwise.
  843. */
  844. public native boolean send (byte [] msg, int flags);
  845. /**
  846. * Receive a message.
  847. *
  848. * @param flags
  849. * the flags to apply to the receive operation.
  850. * @return the message received, as an array of bytes; null on error.
  851. */
  852. public native byte [] recv (int flags);
  853. /**
  854. * Receive a message in to a specified buffer.
  855. *
  856. * @param buffer
  857. * byte[] to copy zmq message payload in to.
  858. * @param offset
  859. * offset in buffer to write data
  860. * @param len
  861. * max bytes to write to buffer.
  862. * If len is smaller than the incoming message size,
  863. * the message will be truncated.
  864. * @param flags
  865. * the flags to apply to the receive operation.
  866. * @return the number of bytes read, -1 on error
  867. */
  868. public native int recv (byte[] buffer, int offset, int len, int flags);
  869. /**
  870. * Class constructor.
  871. *
  872. * @param context
  873. * a 0MQ context previously created.
  874. * @param type
  875. * the socket type.
  876. */
  877. protected Socket (Context context, int type) {
  878. // We keep a local handle to context so that
  879. // garbage collection won't be too greedy on it.
  880. this.context = context;
  881. construct (context, type);
  882. }
  883. /** Initialize the JNI interface */
  884. protected native void construct (Context ctx, int type);
  885. /** Free all resources used by JNI interface. */
  886. @Override
  887. protected native void finalize ();
  888. /**
  889. * Get the socket option value, as a long.
  890. *
  891. * @param option
  892. * ID of the option to set.
  893. * @return The socket option value (as a long).
  894. */
  895. protected native long getLongSockopt (int option);
  896. /**
  897. * Get the socket option value, as a byte array.
  898. *
  899. * @param option
  900. * ID of the option to set.
  901. * @return The socket option value (as a byte array).
  902. */
  903. protected native byte [] getBytesSockopt (int option);
  904. /**
  905. * Set the socket option value, given as a long.
  906. *
  907. * @param option
  908. * ID of the option to set.
  909. * @param optval
  910. * value (as a long) to set the option to.
  911. */
  912. protected native void setLongSockopt (int option, long optval);
  913. /**
  914. * Set the socket option value, given as a byte array.
  915. *
  916. * @param option
  917. * ID of the option to set.
  918. * @param optval
  919. * value (as a byte array) to set the option to.
  920. */
  921. protected native void setBytesSockopt (int option, byte [] optval);
  922. /**
  923. * Get the underlying socket handle. This is private because it is only accessed from JNI,
  924. * where Java access controls are ignored.
  925. *
  926. * @return the internal 0MQ socket handle.
  927. */
  928. private long getSocketHandle () {
  929. return this.socketHandle;
  930. }
  931. /** Opaque data used by JNI driver. */
  932. private long socketHandle;
  933. private Context context = null;
  934. // private Constants use the appropriate setter instead.
  935. private static final int HWM = 1;
  936. // public static final int LWM = 2; // No longer supported
  937. private static final int SWAP = 3;
  938. private static final int AFFINITY = 4;
  939. private static final int IDENTITY = 5;
  940. private static final int SUBSCRIBE = 6;
  941. private static final int UNSUBSCRIBE = 7;
  942. private static final int RATE = 8;
  943. private static final int RECOVERY_IVL = 9;
  944. private static final int MCAST_LOOP = 10;
  945. private static final int SNDBUF = 11;
  946. private static final int RCVBUF = 12;
  947. private static final int RCVMORE = 13;
  948. private static final int FD = 14;
  949. private static final int EVENTS = 15;
  950. private static final int TYPE = 16;
  951. private static final int LINGER = 17;
  952. private static final int RECONNECT_IVL = 18;
  953. private static final int BACKLOG = 19;
  954. private static final int RECONNECT_IVL_MAX = 21;
  955. private static final int MAXMSGSIZE = 22;
  956. private static final int SNDHWM = 23;
  957. private static final int RCVHWM = 24;
  958. private static final int MULTICAST_HOPS = 25;
  959. private static final int RCVTIMEO = 27;
  960. private static final int SNDTIMEO = 28;
  961. }
  962. /**
  963. * Inner class: Poller.
  964. */
  965. public static class Poller {
  966. /**
  967. * These values can be ORed to specify what we want to poll for.
  968. */
  969. public static final int POLLIN = 1;
  970. public static final int POLLOUT = 2;
  971. public static final int POLLERR = 4;
  972. /**
  973. * Register a Socket for polling on all events.
  974. *
  975. * @param socket
  976. * the Socket we are registering.
  977. * @return the index identifying this Socket in the poll set.
  978. */
  979. public int register (Socket socket) {
  980. return register (socket, POLLIN | POLLOUT | POLLERR);
  981. }
  982. /**
  983. * Register a Socket for polling on the specified events.
  984. *
  985. * Automatically grow the internal representation if needed.
  986. *
  987. * @param socket
  988. * the Socket we are registering.
  989. * @param events
  990. * a mask composed by XORing POLLIN, POLLOUT and POLLERR.
  991. * @return the index identifying this Socket in the poll set.
  992. */
  993. public int register (Socket socket, int events) {
  994. int pos = -1;
  995. if (! this.freeSlots.isEmpty()) {
  996. // If there are free slots in our array, remove one
  997. // from the free list and use it.
  998. pos = this.freeSlots.remove();
  999. } else {
  1000. if (this.next >= this.size) {
  1001. // It is necessary to grow the arrays.
  1002. // Compute new size for internal arrays.
  1003. int nsize = this.size + SIZE_INCREMENT;
  1004. // Create new internal arrays.
  1005. Socket [] ns = new Socket [nsize];
  1006. short [] ne = new short [nsize];
  1007. short [] nr = new short [nsize];
  1008. // Copy contents of current arrays into new arrays.
  1009. for (int i = 0; i < this.next; ++i) {
  1010. ns[i] = this.sockets[i];
  1011. ne[i] = this.events[i];
  1012. nr[i] = this.revents[i];
  1013. }
  1014. // Swap internal arrays and size to new values.
  1015. this.size = nsize;
  1016. this.sockets = ns;
  1017. this.events = ne;
  1018. this.revents = nr;
  1019. }
  1020. pos = this.next++;
  1021. }
  1022. this.sockets[pos] = socket;
  1023. this.events[pos] = (short) events;
  1024. this.used++;
  1025. return pos;
  1026. }
  1027. /**
  1028. * Unregister a Socket for polling on the specified events.
  1029. *
  1030. * @param socket
  1031. * the Socket to be unregistered
  1032. */
  1033. public void unregister (Socket socket) {
  1034. for (int i = 0; i < this.next; ++i) {
  1035. if (this.sockets[i] == socket) {
  1036. this.sockets[i] = null;
  1037. this.events[i] = 0;
  1038. this.revents[i] = 0;
  1039. this.freeSlots.add(i);
  1040. --this.used;
  1041. break;
  1042. }
  1043. }
  1044. }
  1045. /**
  1046. * Get the socket associated with an index.
  1047. *
  1048. * @param index
  1049. * the desired index.
  1050. * @return the Socket associated with that index (or null).
  1051. */
  1052. public Socket getSocket (int index) {
  1053. if (index < 0 || index >= this.next)
  1054. return null;
  1055. return this.sockets [index];
  1056. }
  1057. /**
  1058. * Get the current poll timeout.
  1059. *
  1060. * @return the current poll timeout in microseconds.
  1061. * @deprecated Timeout handling has been moved to the poll() methods.
  1062. */
  1063. public long getTimeout () {
  1064. return this.timeout;
  1065. }
  1066. /**
  1067. * Set the poll timeout.
  1068. *
  1069. * @param timeout
  1070. * the desired poll timeout in microseconds.
  1071. * @deprecated Timeout handling has been moved to the poll() methods.
  1072. */
  1073. public void setTimeout (long timeout) {
  1074. if (timeout < -1)
  1075. return;
  1076. this.timeout = timeout;
  1077. }
  1078. /**
  1079. * Get the current poll set size.
  1080. *
  1081. * @return the current poll set size.
  1082. */
  1083. public int getSize () {
  1084. return this.size;
  1085. }
  1086. /**
  1087. * Get the index for the next position in the poll set size.
  1088. *
  1089. * @return the index for the next position in the poll set size.
  1090. */
  1091. public int getNext () {
  1092. return this.next;
  1093. }
  1094. /**
  1095. * Issue a poll call. If the poller's internal timeout value
  1096. * has been set, use that value as timeout; otherwise, block
  1097. * indefinitely.
  1098. *
  1099. * @return how many objects where signalled by poll ().
  1100. */
  1101. public long poll () {
  1102. long tout = -1;
  1103. if (this.timeout > -1) {
  1104. tout = this.timeout;
  1105. }
  1106. return poll(tout);
  1107. }
  1108. /**
  1109. * Issue a poll call, using the specified timeout value.
  1110. * <p>
  1111. * Since ZeroMQ 3.0, the timeout parameter is in <i>milliseconds<i>,
  1112. * but prior to this the unit was <i>microseconds</i>.
  1113. *
  1114. * @param tout
  1115. * the timeout, as per zmq_poll ();
  1116. * if -1, it will block indefinitely until an event
  1117. * happens; if 0, it will return immediately;
  1118. * otherwise, it will wait for at most that many
  1119. * milliseconds/microseconds (see above).
  1120. *
  1121. * @see http://api.zeromq.org/2-1:zmq-poll
  1122. * @see http://api.zeromq.org/3-0:zmq-poll
  1123. *
  1124. * @return how many objects where signalled by poll ()
  1125. */
  1126. public long poll (long tout) {
  1127. if (tout < -1) {
  1128. return 0;
  1129. }
  1130. if (this.size <= 0 || this.next <= 0) {
  1131. return 0;
  1132. }
  1133. for (int i = 0; i < this.next; ++i) {
  1134. this.revents [i] = 0;
  1135. }
  1136. return run_poll (this.used, this.sockets, this.events, this.revents, tout);
  1137. }
  1138. /**
  1139. * Check whether the specified element in the poll set was signalled for input.
  1140. *
  1141. * @param index
  1142. *
  1143. * @return true if the element was signalled.
  1144. */
  1145. public boolean pollin (int index) {
  1146. return poll_mask (index, POLLIN);
  1147. }
  1148. /**
  1149. * Check whether the specified element in the poll set was signalled for output.
  1150. *
  1151. * @param index
  1152. *
  1153. * @return true if the element was signalled.
  1154. */
  1155. public boolean pollout (int index) {
  1156. return poll_mask (index, POLLOUT);
  1157. }
  1158. /**
  1159. * Check whether the specified element in the poll set was signalled for error.
  1160. *
  1161. * @param index
  1162. *
  1163. * @return true if the element was signalled.
  1164. */
  1165. public boolean pollerr (int index) {
  1166. return poll_mask (index, POLLERR);
  1167. }
  1168. /**
  1169. * Class constructor.
  1170. *
  1171. * @param context
  1172. * a 0MQ context previously created.
  1173. */
  1174. protected Poller (Context context) {
  1175. this(context, SIZE_DEFAULT);
  1176. }
  1177. /**
  1178. * Class constructor.
  1179. *
  1180. * @param context
  1181. * a 0MQ context previously created.
  1182. * @param size
  1183. * the number of Sockets this poller will contain.
  1184. */
  1185. protected Poller (Context context, int size) {
  1186. this.context = context;
  1187. this.size = size;
  1188. this.next = 0;
  1189. this.sockets = new Socket [this.size];
  1190. this.events = new short [this.size];
  1191. this.revents = new short [this.size];
  1192. freeSlots = new LinkedList<Integer>();
  1193. }
  1194. /**
  1195. * Issue a poll call on the specified 0MQ sockets.
  1196. * <p>
  1197. * Since ZeroMQ 3.0, the timeout parameter is in <i>milliseconds<i>,
  1198. * but prior to this the unit was <i>microseconds</i>.
  1199. *
  1200. * @param sockets
  1201. * an array of 0MQ Socket objects to poll.
  1202. * @param events
  1203. * an array of short values specifying what to poll for.
  1204. * @param revents
  1205. * an array of short values with the results.
  1206. * @param timeout
  1207. * the maximum timeout in milliseconds/microseconds (see above).
  1208. * @return how many objects where signalled by poll ().
  1209. * @see http://api.zeromq.org/2-1:zmq-poll
  1210. * @see http://api.zeromq.org/3-0:zmq-poll
  1211. */
  1212. private native long run_poll (int count, Socket [] sockets, short [] events, short [] revents, long timeout);
  1213. /**
  1214. * Check whether a specific mask was signalled by latest poll call.
  1215. *
  1216. * @param index
  1217. * the index indicating the socket.
  1218. * @param mask
  1219. * a combination of POLLIN, POLLOUT and POLLERR.
  1220. * @return true if specific socket was signalled as specified.
  1221. */
  1222. private boolean poll_mask (int index, int mask) {
  1223. if (mask <= 0 || index < 0 || index >= this.next) {
  1224. return false;
  1225. }
  1226. return (this.revents [index] & mask) > 0;
  1227. }
  1228. private Context context = null;
  1229. private long timeout = -2; // mark as uninitialized
  1230. private int size = 0;
  1231. private int next = 0;
  1232. private int used = 0;
  1233. private Socket [] sockets = null;
  1234. private short [] events = null;
  1235. private short [] revents = null;
  1236. // When socket is removed from polling, store free slots here
  1237. private LinkedList<Integer> freeSlots = null;
  1238. private static final int SIZE_DEFAULT = 32;
  1239. private static final int SIZE_INCREMENT = 16;
  1240. }
  1241. }