-
Notifications
You must be signed in to change notification settings - Fork 750
/
Copy pathSocketBase.cs
1779 lines (1530 loc) · 69.6 KB
/
SocketBase.cs
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2009-2011 250bpm s.r.o.
Copyright (c) 2007-2009 iMatix Corporation
Copyright (c) 2011 VMware, Inc.
Copyright (c) 2007-2015 Other contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using AsyncIO;
using NetMQ.Core.Patterns;
using NetMQ.Core.Transports.Ipc;
using NetMQ.Core.Transports.Pgm;
using NetMQ.Core.Transports.Tcp;
using NetMQ.Core.Utils;
using TcpListener = NetMQ.Core.Transports.Tcp.TcpListener;
namespace NetMQ.Core
{
internal abstract class SocketBase : Own, IPollEvents, Pipe.IPipeEvents
{
private class Endpoint
{
public Endpoint(Own own, Pipe? pipe)
{
Own = own;
Pipe = pipe;
}
public Own Own { get; }
public Pipe? Pipe { get; }
}
private readonly Dictionary<string, Endpoint> m_endpoints = new Dictionary<string, Endpoint>();
private readonly Dictionary<string, Pipe> m_inprocs = new Dictionary<string, Pipe>();
private bool m_disposed;
/// <summary>If true, associated context was already terminated.</summary>
private bool m_isStopped;
/// <summary>
/// If true, object should have been already destroyed. However,
/// destruction is delayed while we unwind the stack to the point
/// where it doesn't intersect the object being destroyed.
/// </summary>
private bool m_destroyed;
/// <summary>Socket's mailbox object.</summary>
private readonly IMailbox m_mailbox;
/// <summary>List of attached pipes.</summary>
private readonly List<Pipe> m_pipes = new List<Pipe>();
/// <summary>Reaper's poller.</summary>
private Poller? m_poller;
/// <summary>The handle of this socket within the reaper's poller.</summary>
private Socket? m_handle;
/// <summary>Timestamp of when commands were processed the last time.</summary>
private long m_lastTsc;
/// <summary>Number of messages received since last command processing.</summary>
private int m_ticks;
/// <summary>True if the last message received had MORE flag set.</summary>
private bool m_rcvMore;
/// <summary>Monitor socket.</summary>
private SocketBase? m_monitorSocket;
/// <summary>Bitmask of events being monitored.</summary>
private SocketEvents m_monitorEvents;
/// <summary>The tcp port that was bound to, if any.</summary>
private int m_port;
/// <summary>
/// Indicate if the socket is thread safe
/// </summary>
private bool m_threadSafe;
/// <summary>
/// Mutex for synchronize access to the socket in thread safe mode
/// </summary>
private object m_threadSafeSync = new object();
/// <summary>
/// Signaler to be used in the reaping stage
/// </summary>
private Signaler? m_reaperSignaler = null;
/// <summary>
/// Create a new SocketBase within the given Ctx, with the specified thread-id and socket-id.
/// </summary>
/// <param name="parent">the Ctx context that this socket will live within</param>
/// <param name="threadId">the id of the thread upon which this socket will execute</param>
/// <param name="socketId">the integer id for the new socket</param>
/// <param name="threadSafe">Indicate if the socket is thread-safe</param>
protected SocketBase(Ctx parent, int threadId, int socketId, bool threadSafe = false)
: base(parent, threadId)
{
m_options.SocketId = socketId;
m_threadSafe = threadSafe;
if (threadSafe)
m_mailbox = new MailboxSafe("safe-socket-" + socketId, m_threadSafeSync);
else
m_mailbox = new Mailbox("socket-" + socketId);
}
// Note: Concrete algorithms for the x- methods are to be defined by
// individual socket types.
/// <summary>
/// Abstract method for attaching a given pipe to this socket.
/// The concrete implementations are defined by the individual socket types.
/// </summary>
/// <param name="pipe">the Pipe to attach</param>
/// <param name="icanhasall">if true - subscribe to all data on the pipe</param>
protected abstract void XAttachPipe(Pipe pipe, bool icanhasall);
/// <summary>
/// Abstract method that gets called to signal that the given pipe is to be removed from this socket.
/// The concrete implementations of SocketBase override this to provide their own implementation
/// of how to terminate the pipe.
/// </summary>
/// <param name="pipe">the Pipe that is being removed</param>
protected abstract void XTerminated(Pipe pipe);
/// <summary>Throw <see cref="ObjectDisposedException"/> if this socket is already disposed.</summary>
/// <exception cref="ObjectDisposedException">This object is already disposed.</exception>
public void CheckDisposed()
{
if (m_disposed)
throw new ObjectDisposedException(GetType().FullName);
}
/// <summary>
/// Throw <see cref="TerminatingException"/> if the message-queueing system has started terminating.
/// </summary>
/// <exception cref="TerminatingException">The socket has been stopped.</exception>
private void CheckContextTerminated()
{
if (m_isStopped)
throw new TerminatingException(innerException: null, message: "CheckContextTerminated - yes, is terminated.");
}
/// <summary>
/// Create a socket of a specified type.
/// </summary>
/// <param name="type">a ZmqSocketType specifying the type of socket to create</param>
/// <param name="parent">the parent context</param>
/// <param name="threadId">the thread for this new socket to run on</param>
/// <param name="socketId">an integer id for this socket</param>
/// <exception cref="InvalidException">The socket type must be valid.</exception>
public static SocketBase Create(ZmqSocketType type, Ctx parent, int threadId, int socketId)
{
switch (type)
{
case ZmqSocketType.Pair:
return new Pair(parent, threadId, socketId);
case ZmqSocketType.Pub:
return new Pub(parent, threadId, socketId);
case ZmqSocketType.Sub:
return new Sub(parent, threadId, socketId);
case ZmqSocketType.Req:
return new Req(parent, threadId, socketId);
case ZmqSocketType.Rep:
return new Rep(parent, threadId, socketId);
case ZmqSocketType.Dealer:
return new Dealer(parent, threadId, socketId);
case ZmqSocketType.Router:
return new Router(parent, threadId, socketId);
case ZmqSocketType.Pull:
return new Pull(parent, threadId, socketId);
case ZmqSocketType.Push:
return new Push(parent, threadId, socketId);
case ZmqSocketType.Xpub:
return new XPub(parent, threadId, socketId);
case ZmqSocketType.Xsub:
return new XSub(parent, threadId, socketId);
case ZmqSocketType.Stream:
return new Stream(parent, threadId, socketId);
case ZmqSocketType.Peer:
return new Peer(parent, threadId, socketId);
case ZmqSocketType.Server:
return new Server(parent, threadId, socketId);
case ZmqSocketType.Client:
return new Client(parent, threadId, socketId);
case ZmqSocketType.Radio:
return new Radio(parent, threadId, socketId);
case ZmqSocketType.Dish:
return new Dish(parent, threadId, socketId);
case ZmqSocketType.Gather:
return new Gather(parent, threadId, socketId);
case ZmqSocketType.Scatter:
return new Scatter(parent, threadId, socketId);
default:
throw new InvalidException("SocketBase.Create called with invalid type of " + type);
}
}
/// <summary>
/// Destroy this socket - which means to stop monitoring the queue for messages.
/// This simply calls StopMonitor, and then verifies that the destroyed-flag is set.
/// </summary>
public override void Destroy()
{
StopMonitor();
m_reaperSignaler?.Close();
Debug.Assert(m_destroyed);
}
/// <summary>
/// Return the Mailbox associated with this socket.
/// </summary>
public IMailbox Mailbox => m_mailbox;
/// <summary>
/// Interrupt a blocking call if the socket is stuck in one.
/// This function can be called from a different thread!
/// </summary>
public void Stop()
{
// Called by ctx when it is terminated (zmq_term).
// 'stop' command is sent from the threads that called zmq_term to
// the thread owning the socket. This way, blocking call in the
// owner thread can be interrupted.
SendStop();
}
/// <summary>
/// Check whether the transport protocol, as specified in connect or
/// bind, is available and compatible with the socket type.
/// </summary>
/// <exception cref="ProtocolNotSupportedException">the specified protocol is not supported</exception>
/// <exception cref="ProtocolNotSupportedException">the socket type and protocol do not match</exception>
/// <remarks>
/// The supported protocols are "inproc", "ipc", "tcp", "pgm", and "epgm".
/// If the protocol is either "pgm" or "epgm", then this socket must be of type Pub, Sub, XPub, or XSub.
/// </remarks>
private void CheckProtocol(string protocol)
{
switch (protocol)
{
case Address.InProcProtocol:
case Address.IpcProtocol:
case Address.TcpProtocol:
// All is well
break;
case Address.PgmProtocol:
case Address.EpgmProtocol:
// Check whether socket type and transport protocol match.
// Specifically, multicast protocols can't be combined with
// bi-directional messaging patterns (socket types).
switch (m_options.SocketType)
{
case ZmqSocketType.Pub:
case ZmqSocketType.Sub:
case ZmqSocketType.Xpub:
case ZmqSocketType.Xsub:
// All is well
break;
default:
throw new ProtocolNotSupportedException(
"Multicast protocols are not supported by socket type: " + m_options.SocketType);
}
break;
default:
throw new ProtocolNotSupportedException("Invalid protocol: " + protocol);
}
}
/// <summary>
/// Register the given pipe with this socket.
/// </summary>
/// <param name="pipe">the Pipe to attach</param>
/// <param name="icanhasall">if true - subscribe to all data on the pipe (optional - default is false)</param>
private void AttachPipe(Pipe pipe, bool icanhasall = false)
{
// First, register the pipe so that we can terminate it later on.
pipe.SetEventSink(this);
m_pipes.Add(pipe);
// Let the derived socket type know about new pipe.
XAttachPipe(pipe, icanhasall);
// If the socket is already being closed, ask any new pipes to terminate
// straight away.
if (IsTerminating)
{
RegisterTermAcks(1);
pipe.Terminate(false);
}
}
/// <summary>
/// Set the specified socket option.
/// </summary>
/// <param name="option">which option to set</param>
/// <param name="optionValue">the value to set the option to</param>
/// <exception cref="TerminatingException">The socket has been stopped.</exception>
public void SetSocketOption(ZmqSocketOption option, object? optionValue)
{
Lock();
try
{
CheckContextTerminated();
// First, check whether specific socket type overloads the option.
if (!XSetSocketOption(option, optionValue))
{
// If the socket type doesn't support the option, pass it to
// the generic option parser.
m_options.SetSocketOption(option, optionValue);
}
}
finally
{
Unlock();
}
}
/// <summary>
/// Return the integer-value of the specified option.
/// </summary>
/// <param name="option">which option to get</param>
/// <returns>the value of the specified option, or -1 if error</returns>
/// <exception cref="TerminatingException">The socket has been stopped.</exception>
/// <remarks>
/// If the ReceiveMore option is specified, then 1 is returned if it is true, 0 if it is false.
/// If the Events option is specified, then process any outstanding commands, and return -1 if that throws a TerminatingException.
/// then return an integer that is the bitwise-OR of the PollEvents.PollOut and PollEvents.PollIn flags.
/// Otherwise, cast the specified option value to an integer and return it.
/// </remarks>
public int GetSocketOption(ZmqSocketOption option)
{
Lock();
try
{
CheckContextTerminated();
if (option == ZmqSocketOption.ReceiveMore)
{
return m_rcvMore ? 1 : 0;
}
if (option == ZmqSocketOption.Events)
{
try
{
ProcessCommands(0, false);
}
catch (TerminatingException)
{
return -1;
}
PollEvents val = 0;
if (HasOut())
val |= PollEvents.PollOut;
if (HasIn())
val |= PollEvents.PollIn;
return (int)val;
}
return (int)GetSocketOptionX(option)!;
}
finally
{
Unlock();
}
}
/// <summary>
/// Return the value of the specified option as an Object.
/// </summary>
/// <param name="option">which option to get</param>
/// <returns>the value of the option</returns>
/// <exception cref="TerminatingException">The socket has already been stopped.</exception>
/// <remarks>
/// If the Handle option is specified, then return the handle of the contained mailbox.
/// If the Events option is specified, then process any outstanding commands, and return -1 if that throws a TerminatingException.
/// then return a PollEvents that is the bitwise-OR of the PollEvents.PollOut and PollEvents.PollIn flags.
/// </remarks>
public object? GetSocketOptionX(ZmqSocketOption option)
{
Lock();
try
{
CheckContextTerminated();
if (option == ZmqSocketOption.ReceiveMore)
{
return m_rcvMore;
}
if (option == ZmqSocketOption.Handle)
{
if (m_threadSafe)
throw new InvalidException();
return ((Mailbox) m_mailbox).Handle;
}
if (option == ZmqSocketOption.Events)
{
try
{
ProcessCommands(0, false);
}
catch (TerminatingException)
{
return -1;
}
PollEvents val = 0;
if (HasOut())
val |= PollEvents.PollOut;
if (HasIn())
val |= PollEvents.PollIn;
return val;
}
// If the socket type doesn't support the option, pass it to
// the generic option parser.
return m_options.GetSocketOption(option);
}
finally
{
Unlock();
}
}
/// <summary>
/// Join the dish socket to a group
/// </summary>
/// <param name="group">The group to join</param>
public void Join(string group)
{
Lock();
try
{
XJoin(group);
}
finally
{
Unlock();
}
}
/// <summary>
/// Leave a group for a dish socket
/// </summary>
/// <param name="group">The group leave</param>
public void Leave(string group)
{
Lock();
try
{
XLeave(group);
}
finally
{
Unlock();
}
}
/// <summary>
/// Bind this socket to the given address.
/// </summary>
/// <param name="addr">a string denoting the endpoint-address to bind to</param>
/// <exception cref="AddressAlreadyInUseException">the address specified to bind to must not be already in use</exception>
/// <exception cref="ArgumentException">The requested protocol is not supported.</exception>
/// <exception cref="FaultException">the socket bind failed</exception>
/// <exception cref="NetMQException">No IO thread was found, or the protocol's listener encountered an
/// error during initialisation.</exception>
/// <exception cref="ProtocolNotSupportedException">the specified protocol is not supported</exception>
/// <exception cref="ProtocolNotSupportedException">the socket type and protocol do not match</exception>
/// <exception cref="TerminatingException">The socket has been stopped.</exception>
/// <remarks>
/// The supported protocols are "inproc", "ipc", "tcp", "pgm", and "epgm".
/// If the protocol is either "pgm" or "epgm", then this socket must be of type Pub, Sub, XPub, or XSub.
/// If the protocol is "inproc", you cannot bind to the same address more than once.
/// </remarks>
public void Bind(string addr)
{
Lock();
try
{
CheckContextTerminated();
// Process pending commands, if any.
ProcessCommands(0, false);
DecodeAddress(addr, out string address, out string protocol);
CheckProtocol(protocol);
switch (protocol)
{
case Address.InProcProtocol:
{
var endpoint = new Ctx.Endpoint(this, m_options);
bool addressRegistered = RegisterEndpoint(addr, endpoint);
if (!addressRegistered)
throw new AddressAlreadyInUseException($"Cannot bind address ( {addr} ) - already in use.");
m_options.LastEndpoint = addr;
return;
}
case Address.PgmProtocol:
case Address.EpgmProtocol:
{
if (m_options.SocketType == ZmqSocketType.Pub || m_options.SocketType == ZmqSocketType.Xpub)
{
// For convenience's sake, bind can be used interchangeable with
// connect for PGM and EPGM transports.
Connect(addr);
return;
}
break;
}
}
// Remaining transports require to be run in an I/O thread, so at this
// point we'll choose one.
var ioThread = ChooseIOThread(m_options.Affinity);
if (ioThread == null)
throw NetMQException.Create(ErrorCode.EmptyThread);
switch (protocol)
{
case Address.TcpProtocol:
{
var listener = new TcpListener(ioThread, this, m_options);
try
{
listener.SetAddress(address);
m_port = listener.Port;
// Recreate the address string (localhost:1234) in case the port was system-assigned
addr = $"tcp://{address.Substring(0, address.IndexOf(':'))}:{m_port}";
}
catch (NetMQException ex)
{
listener.Destroy();
EventBindFailed(addr, ex.ErrorCode);
throw;
}
m_options.LastEndpoint = listener.Address;
AddEndpoint(addr, listener, null);
break;
}
case Address.PgmProtocol:
case Address.EpgmProtocol:
{
var listener = new PgmListener(ioThread, this, m_options);
try
{
listener.Init(address);
}
catch (NetMQException ex)
{
listener.Destroy();
EventBindFailed(addr, ex.ErrorCode);
throw;
}
m_options.LastEndpoint = addr;
AddEndpoint(addr, listener, null);
break;
}
case Address.IpcProtocol:
{
var listener = new IpcListener(ioThread, this, m_options);
try
{
listener.SetAddress(address);
m_port = listener.Port;
}
catch (NetMQException ex)
{
listener.Destroy();
EventBindFailed(addr, ex.ErrorCode);
throw;
}
m_options.LastEndpoint = listener.Address;
AddEndpoint(addr, listener, null);
break;
}
default:
{
throw new ArgumentException($"Address {addr} has unsupported protocol: {protocol}",
nameof(addr));
}
}
}
finally
{
Unlock();
}
}
/// <summary>Bind the specified TCP address to an available port, assigned by the operating system.</summary>
/// <param name="addr">a string denoting the endpoint to bind to</param>
/// <returns>the port-number that was bound to</returns>
/// <exception cref="ProtocolNotSupportedException"><paramref name="addr"/> uses a protocol other than TCP.</exception>
/// <exception cref="TerminatingException">The socket has been stopped.</exception>
/// <exception cref="AddressAlreadyInUseException">The specified address is already in use.</exception>
/// <exception cref="NetMQException">No IO thread was found, or the protocol's listener errored during
/// initialisation.</exception>
/// <exception cref="FaultException">the socket bind failed</exception>
public int BindRandomPort(string addr)
{
Lock();
try
{
DecodeAddress(addr, out string address, out string protocol);
if (protocol != Address.TcpProtocol)
throw new ProtocolNotSupportedException("Address must use the TCP protocol.");
Bind(addr + ":0");
return m_port;
}
finally
{
Unlock();
}
}
/// <summary>
/// Connect this socket to the given address.
/// </summary>
/// <param name="addr">a string denoting the endpoint to connect to</param>
/// <exception cref="AddressAlreadyInUseException">The specified address is already in use.</exception>
/// <exception cref="NetMQException">No IO thread was found.</exception>
/// <exception cref="ProtocolNotSupportedException">the specified protocol is not supported</exception>
/// <exception cref="ProtocolNotSupportedException">the socket type and protocol do not match</exception>
/// <exception cref="TerminatingException">The socket has been stopped.</exception>
/// <remarks>
/// The supported protocols are "inproc", "ipc", "tcp", "pgm", and "epgm".
/// If the protocol is either "pgm" or "epgm", then this socket must be of type Pub, Sub, XPub, or XSub.
/// </remarks>
/// <exception cref="EndpointNotFoundException">The given address was not found in the list of endpoints.</exception>
public void Connect(string addr)
{
Lock();
try
{
CheckContextTerminated();
// Process pending commands, if any.
ProcessCommands(0, false);
DecodeAddress(addr, out string address, out string protocol);
CheckProtocol(protocol);
if (protocol == Address.InProcProtocol)
{
// TODO: inproc connect is specific with respect to creating pipes
// as there's no 'reconnect' functionality implemented. Once that
// is in place we should follow generic pipe creation algorithm.
// Find the peer endpoint.
Ctx.Endpoint peer = FindEndpoint(addr);
// The total HWM for an inproc connection should be the sum of
// the binder's HWM and the connector's HWM.
var sndhwm = m_options.SendHighWatermark != 0 && peer.Options.ReceiveHighWatermark != 0
? m_options.SendHighWatermark + peer.Options.ReceiveHighWatermark
: 0;
var rcvhwm = m_options.ReceiveHighWatermark != 0 && peer.Options.SendHighWatermark != 0
? m_options.ReceiveHighWatermark + peer.Options.SendHighWatermark
: 0;
// The total LWM for an inproc connection should be the sum of
// the binder's LWM and the connector's LWM.
int sndlwm = m_options.SendLowWatermark != 0 && peer.Options.ReceiveLowWatermark != 0
? m_options.SendLowWatermark + peer.Options.ReceiveLowWatermark
: 0;
int rcvlwm = m_options.ReceiveLowWatermark != 0 && peer.Options.SendLowWatermark != 0
? m_options.ReceiveLowWatermark + peer.Options.SendLowWatermark
: 0;
// Create a bi-directional pipe to connect the peers.
ZObject[] parents = { this, peer.Socket };
int[] highWaterMarks = { sndhwm, rcvhwm };
int[] lowWaterMarks = { sndlwm, rcvlwm };
Pipe[] pipes = Pipe.PipePair(parents, highWaterMarks, lowWaterMarks);
// Attach local end of the pipe to this socket object.
AttachPipe(pipes[0]);
// If required, send the identity of the local socket to the peer.
if (peer.Options.RecvIdentity)
{
var id = new Msg();
id.InitPool(m_options.IdentitySize);
id.Put(m_options.Identity, 0, m_options.IdentitySize);
id.SetFlags(MsgFlags.Identity);
bool written = pipes[0].Write(ref id);
Debug.Assert(written);
pipes[0].Flush();
}
// If required, send the identity of the peer to the local socket.
if (m_options.RecvIdentity)
{
var id = new Msg();
id.InitPool(peer.Options.IdentitySize);
id.Put(peer.Options.Identity, 0, peer.Options.IdentitySize);
id.SetFlags(MsgFlags.Identity);
bool written = pipes[1].Write(ref id);
Debug.Assert(written);
pipes[1].Flush();
}
// If set, send the hello msg of the local socket to the peer.
if (m_options.CanSendHelloMsg && m_options.HelloMsg != null)
{
var helloMsg = new Msg();
helloMsg.InitPool(m_options.HelloMsg.Length);
helloMsg.Put(m_options.HelloMsg, 0, m_options.HelloMsg.Length);
bool written = pipes[0].Write(ref helloMsg);
Debug.Assert(written);
pipes[0].Flush();
}
// If set, send the hello msg of the peer to the local socket.
if (peer.Options.CanSendHelloMsg && peer.Options.HelloMsg != null)
{
var helloMsg = new Msg();
helloMsg.InitPool(peer.Options.HelloMsg.Length);
helloMsg.Put(peer.Options.HelloMsg, 0, peer.Options.HelloMsg.Length);
bool written = pipes[1].Write(ref helloMsg);
Debug.Assert(written);
pipes[1].Flush();
}
// Attach remote end of the pipe to the peer socket. Note that peer's
// seqnum was incremented in find_endpoint function. We don't need it
// increased here.
SendBind(peer.Socket, pipes[1], false);
// Save last endpoint URI
m_options.LastEndpoint = addr;
// remember inproc connections for disconnect
m_inprocs.Add(addr, pipes[0]);
return;
}
// Choose the I/O thread to run the session in.
var ioThread = ChooseIOThread(m_options.Affinity);
if (ioThread == null)
throw NetMQException.Create(ErrorCode.EmptyThread);
var paddr = new Address(protocol, address);
// Resolve address (if needed by the protocol)
switch (protocol)
{
case Address.TcpProtocol:
{
paddr.Resolved = (new TcpAddress());
paddr.Resolved.Resolve(address, m_options.IPv4Only);
break;
}
case Address.IpcProtocol:
{
paddr.Resolved = (new IpcAddress());
paddr.Resolved.Resolve(address, true);
break;
}
case Address.PgmProtocol:
case Address.EpgmProtocol:
{
if (m_options.SocketType == ZmqSocketType.Sub || m_options.SocketType == ZmqSocketType.Xsub)
{
Bind(addr);
return;
}
paddr.Resolved = new PgmAddress();
paddr.Resolved.Resolve(address, m_options.IPv4Only);
break;
}
}
// Create session.
SessionBase session = SessionBase.Create(ioThread, true, this, m_options, paddr);
Assumes.NotNull(session);
// PGM does not support subscription forwarding; ask for all data to be
// sent to this pipe.
bool icanhasall = protocol == Address.PgmProtocol || protocol == Address.EpgmProtocol;
Pipe? newPipe = null;
if (!m_options.DelayAttachOnConnect || icanhasall || m_options.SocketType == ZmqSocketType.Peer)
{
// Create a bi-directional pipe.
ZObject[] parents = { this, session };
int[] hwms = { m_options.SendHighWatermark, m_options.ReceiveHighWatermark };
int[] lwms = { m_options.SendLowWatermark, m_options.ReceiveLowWatermark };
Pipe[] pipes = Pipe.PipePair(parents, hwms, lwms);
// Attach local end of the pipe to the socket object.
AttachPipe(pipes[0], icanhasall);
newPipe = pipes[0];
// Attach remote end of the pipe to the session object later on.
session.AttachPipe(pipes[1]);
}
// Save last endpoint URI
m_options.LastEndpoint = paddr.ToString();
AddEndpoint(addr, session, newPipe);
}
finally
{
Unlock();
}
}
/// <summary>
/// Given a string containing an endpoint address like "tcp://127.0.0.1:5555,
/// break-it-down into the address part ("127.0.0.1:5555") and the protocol part ("tcp").
/// </summary>
/// <param name="addr">a string denoting the endpoint, to take the parts from</param>
/// <param name="address">the IP-address portion of the end-point address</param>
/// <param name="protocol">the protocol portion of the end-point address (such as "tcp")</param>
private static void DecodeAddress(string addr, out string address, out string protocol)
{
const string protocolDelimeter = "://";
int protocolDelimeterIndex = addr.IndexOf(protocolDelimeter, StringComparison.Ordinal);
protocol = addr.Substring(0, protocolDelimeterIndex);
address = addr.Substring(protocolDelimeterIndex + protocolDelimeter.Length);
}
/// <summary>
/// Take ownership of the given <paramref name="endpoint"/> and register it against the given <paramref name="address"/>.
/// </summary>
private void AddEndpoint(string address, Own endpoint, Pipe? pipe)
{
// Activate the session. Make it a child of this socket.
LaunchChild(endpoint);
m_endpoints[address] = new Endpoint(endpoint, pipe);
}
/// <summary>
/// Disconnect from the given endpoint.
/// </summary>
/// <param name="addr">the endpoint to disconnect from</param>
/// <exception cref="ArgumentNullException"><paramref name="addr"/> is <c>null</c>.</exception>
/// <exception cref="EndpointNotFoundException">Endpoint was not found and cannot be disconnected.</exception>
/// <exception cref="ProtocolNotSupportedException">The specified protocol must be valid.</exception>
/// <exception cref="TerminatingException">The socket has been stopped.</exception>
public void TermEndpoint(string addr)
{
Lock();
try
{
CheckContextTerminated();
// Check whether endpoint address passed to the function is valid.
if (addr == null)
throw new ArgumentNullException(nameof(addr));
// Process pending commands, if any, since there could be pending unprocessed process_own()'s
// (from launch_child() for example) we're asked to terminate now.
ProcessCommands(0, false);
DecodeAddress(addr, out string address, out string protocol);
CheckProtocol(protocol);
if (protocol == Address.InProcProtocol)
{
if (UnregisterEndpoint(addr, this))
return;
if (!m_inprocs.TryGetValue(addr, out Pipe pipe))
throw new EndpointNotFoundException("Endpoint was not found and cannot be disconnected");
pipe.Terminate(true);
m_inprocs.Remove(addr);
}
else
{
if (!m_endpoints.TryGetValue(addr, out Endpoint endpoint))
throw new EndpointNotFoundException("Endpoint was not found and cannot be disconnected");
endpoint.Pipe?.Terminate(false);
TermChild(endpoint.Own);
m_endpoints.Remove(addr);
}
}
finally
{
Unlock();
}
}
/// <summary>
/// Transmit the given Msg across the message-queueing system.
/// </summary>
/// <param name="msg">The <see cref="Msg"/> to send.</param>
/// <param name="timeout">The timeout to wait before returning <c>false</c>. Pass <see cref="SendReceiveConstants.InfiniteTimeout"/> to disable timeout.</param>
/// <param name="more">Whether this message will contain another frame after this one.</param>
/// <exception cref="TerminatingException">The socket has been stopped.</exception>
/// <exception cref="FaultException"><paramref name="msg"/> is not initialised.</exception>
public bool TrySend(ref Msg msg, TimeSpan timeout, bool more)
{
Lock();
try
{
CheckContextTerminated();
// Check whether message passed to the function is valid.
if (!msg.IsInitialised)
throw new FaultException("SocketBase.Send passed an uninitialised Msg.");
// Process pending commands, if any.
ProcessCommands(0, true);
// Clear any user-visible flags that are set on the message.
msg.ResetFlags(MsgFlags.More);
// At this point we impose the flags on the message.
if (more)
msg.SetFlags(MsgFlags.More);
// Try to send the message.
bool isMessageSent = XSend(ref msg);
if (isMessageSent)
return true;
// In case of non-blocking send we'll simply return false
if (timeout == TimeSpan.Zero)
return false;
// Compute the time when the timeout should occur.
// If the timeout is infinite, don't care.
int timeoutMillis = (int) timeout.TotalMilliseconds;
long end = timeoutMillis < 0 ? 0 : (Clock.NowMs() + timeoutMillis);
// Oops, we couldn't send the message. Wait for the next
// command, process it and try to send the message again.
// If timeout is reached in the meantime, return EAGAIN.
while (true)
{
ProcessCommands(timeoutMillis, false);
isMessageSent = XSend(ref msg);