-
-
Notifications
You must be signed in to change notification settings - Fork 346
/
Socket.class.st
1755 lines (1442 loc) · 62.1 KB
/
Socket.class.st
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
"
A Socket represents a network connection point. Current sockets are designed to support the TCP/IP and UDP protocols. Sockets are the lowest level of networking object in Pharo and are not normally used directly. SocketStream is a higher level object wrapping a Socket in a stream like protocol.
ProtocolClient and subclasses are in turn wrappers around a SocketStream to provide support for specific network protocols such as POP, NNTP, HTTP, and FTP.
"
Class {
#name : 'Socket',
#superclass : 'Object',
#instVars : [
'semaphore',
'socketHandle',
'readSemaphore',
'writeSemaphore'
],
#classVars : [
'Connected',
'DeadServer',
'InvalidSocket',
'OtherEndClosed',
'Registry',
'TCPSocketType',
'ThisEndClosed',
'UDPSocketType',
'Unconnected',
'WaitingForConnection'
],
#category : 'Network-Kernel-Base',
#package : 'Network-Kernel',
#tag : 'Base'
}
{ #category : 'instance creation' }
Socket class >> acceptFrom: aSocket [
^[ super new acceptFrom: aSocket ]
repeatWithGCIf: [ :sock | sock isValid not ]
]
{ #category : 'instance creation' }
Socket class >> createIfFail: failBlock [
"Attempt to create a new socket. If successful, return the new socket. Otherwise, return the result of evaluating the given block. Socket creation can fail if the network isn't available or if there are not sufficient resources available to create another socket."
"Note: The default creates a TCP socket"
^self tcpCreateIfFail: failBlock
]
{ #category : 'utilities' }
Socket class >> deadServer [
^ DeadServer
]
{ #category : 'utilities' }
Socket class >> deadServer: aStringOrNil [
"Keep the machine name of the most recently encoutered non-responding machine. Next time the user can move it to the last in a list of servers to try."
DeadServer := aStringOrNil
]
{ #category : 'class initialization' }
Socket class >> initialize [
"Socket initialize"
"Socket Types"
TCPSocketType := 0.
UDPSocketType := 1.
"Socket Status Values"
InvalidSocket := -1.
Unconnected := 0.
WaitingForConnection := 1.
Connected := 2.
OtherEndClosed := 3.
ThisEndClosed := 4
]
{ #category : 'network initialization' }
Socket class >> initializeNetwork [
"Initialize the network drivers and the NetNameResolver. Do nothing if the network is already initialized."
"Note: The network must be re-initialized every time Pharo starts up, so applications that persist across snapshots should be prepared to re-initialize the network as needed. Such applications should call 'Socket initializeNetwork' before every network transaction. "
NetNameResolver initializeNetwork
]
{ #category : 'tests' }
Socket class >> loopbackTest [
"Send data from one socket to another on the local machine.
Tests most of the socket primitives."
"100 timesRepeat: [Socket loopbackTest]"
| sock1 sock2 bytesToSend sendBuf receiveBuf done bytesSent bytesReceived t extraBytes packetsSent packetsRead |
'
starting loopback test' traceCr.
'---------- Connecting ----------' traceCr.
self initializeNetwork.
sock1 := self new.
sock2 := self new.
sock1 listenOn: 54321.
sock2 connectTo: NetNameResolver localHostAddress port: 54321.
sock1 waitForConnectionFor: self standardTimeout.
sock2 waitForConnectionFor: self standardTimeout.
sock1 isConnected ifFalse: [ self error: 'sock1 not connected' ].
sock2 isConnected ifFalse: [ self error: 'sock2 not connected' ].
'connection established' traceCr.
bytesToSend := 5000000.
sendBuf := String new: 5000 withAll: $x.
receiveBuf := String new: 50000.
done := false.
packetsSent := packetsRead := bytesSent := bytesReceived := 0.
t := [
[ done ] whileFalse: [
(sock1 sendDone and: [ bytesSent < bytesToSend ]) ifTrue: [
packetsSent := packetsSent + 1.
bytesSent := bytesSent + (sock1 sendSomeData: sendBuf) ].
sock2 dataAvailable ifTrue: [
packetsRead := packetsRead + 1.
bytesReceived := bytesReceived
+ (sock2 receiveDataInto: receiveBuf) ].
done := bytesSent >= bytesToSend and: [
bytesReceived = bytesSent ] ] ] millisecondsToRun.
'closing connection' traceCr.
sock1 waitForSendDoneFor: self standardTimeout.
sock1 close.
sock2 waitForDisconnectionFor: self standardTimeout.
extraBytes := sock2 discardReceivedData.
extraBytes > 0 ifTrue: [
' *** received ' , extraBytes size printString
, ' extra bytes ***' traceCr ].
sock2 close.
sock1 waitForDisconnectionFor: self standardTimeout.
sock1 isUnconnectedOrInvalid ifFalse: [
self error: 'sock1 not closed' ].
sock2 isUnconnectedOrInvalid ifFalse: [
self error: 'sock2 not closed' ].
'---------- Connection Closed ----------' traceCr.
sock1 destroy.
sock2 destroy.
('loopback test done; time = ' , t printString) traceCr.
((bytesToSend asFloat / t roundTo: 0.01) printString
, '* 1000 bytes/sec') traceCr.
Smalltalk tools transcript endEntry
]
{ #category : 'utilities' }
Socket class >> nameForWellKnownTCPPort: portNum [
"Answer the name for the given well-known TCP port number. Answer a string containing the port number if it isn't well-known."
| portList |
portList := #(#(7 'echo') #(9 'discard') #(13 'time') #(19 'characterGenerator') #(21 'ftp') #(23 'telnet') #(25 'smtp') #(80 'http') #(110 'pop3') #(119 'nntp')).
^ portList
detect: [ :pair | pair first = portNum ]
ifFound: [ :pair | pair last ]
ifNone: [ 'port-' , portNum printString ]
]
{ #category : 'instance creation' }
Socket class >> new [
"Return a new, unconnected Socket. Note that since socket creation may fail, it is safer to use the method createIfFail: to handle such failures gracefully; this method is primarily for backward compatibility and may be disallowed in a future release."
"Note: The default creates a TCP socket - this is also backward compatibility."
^self newTCP
]
{ #category : 'tests' }
Socket class >> newAcceptCheck [
"Check if the platform has support for the BSD style accept()."
"Socket newAcceptCheck"
| socket |
self initializeNetwork.
socket := self newTCP.
socket listenOn: 44444 backlogSize: 4.
socket isValid ifTrue: [
self inform: 'Everything looks OK for the BSD style accept()'
] ifFalse: [
self inform: 'It appears that you DO NOT have support for the BSD style accept()'].
socket destroy
]
{ #category : 'instance creation' }
Socket class >> newTCP [
"Create a socket and initialize it for TCP"
self initializeNetwork.
^ [ super new initialize: TCPSocketType ] repeatWithGCIf: [ :socket |
socket isValid not ]
]
{ #category : 'instance creation' }
Socket class >> newUDP [
"Create a socket and initialize it for UDP"
self initializeNetwork.
^ [ super new initialize: UDPSocketType ] repeatWithGCIf: [ :socket |
socket isValid not ]
]
{ #category : 'utilities' }
Socket class >> ping: hostName [
"Ping the given host. Useful for checking network connectivity. The host must be running a TCP echo server."
"Socket ping: 'pharo-project.org'"
| tcpPort sock serverAddr startTime echoTime |
tcpPort := 7. "7 = echo port, 13 = time port, 19 = character generator port"
serverAddr := NetNameResolver addressForName: hostName timeout: 10.
serverAddr
ifNil: [ ^ self inform: 'Could not find an address for ' , hostName ].
sock := Socket new.
sock connectNonBlockingTo: serverAddr port: tcpPort.
[ sock waitForConnectionFor: 10 ]
on: ConnectionTimedOut
do: [ :ex |
(self confirm: 'Continue to wait for connection to ' , hostName , '?')
ifTrue: [ ex retry ]
ifFalse: [
sock destroy.
^ self ] ].
sock sendData: 'echo!'.
startTime := Time millisecondClockValue.
[ sock waitForDataFor: 15 ]
on: ConnectionTimedOut
do: [ :ex |
(self confirm: 'Packet sent but no echo yet; keep waiting?')
ifTrue: [ ex retry ] ].
echoTime := Time millisecondsSince: startTime.
sock destroy.
self inform: hostName , ' responded in ' , echoTime printString , ' milliseconds'
]
{ #category : 'utilities' }
Socket class >> pingPorts: portList on: hostName timeOutSecs: timeOutSecs [
"Attempt to connect to each of the given sockets on the given host. Wait at most timeOutSecs for the connections to be established. Answer an array of strings indicating the available ports."
"Socket pingPorts: #(7 13 19 21 23 25 80 110 119) on: 'pharo-project.org' timeOutSecs: 15"
| serverAddr sockets startTime timeoutMsecs done result unconnectedCount connectedCount waitingCount |
serverAddr := NetNameResolver addressForName: hostName timeout: 10.
serverAddr
ifNil: [
self inform: 'Could not find an address for ' , hostName.
^ #() ].
sockets := portList
collect: [ :portNum |
| sock |
sock := Socket new.
sock connectTo: serverAddr port: portNum ].
startTime := Time millisecondClockValue.
timeoutMsecs := (1000 * timeOutSecs) truncated.
done := false.
[ done ]
whileFalse: [
unconnectedCount := 0.
connectedCount := 0.
waitingCount := 0.
sockets
do: [ :s |
s isUnconnectedOrInvalid
ifTrue: [ unconnectedCount := unconnectedCount + 1 ]
ifFalse: [
s isConnected
ifTrue: [ connectedCount := connectedCount + 1 ].
s isWaitingForConnection
ifTrue: [ waitingCount := waitingCount + 1 ] ] ].
waitingCount = 0
ifTrue: [ done := true ].
connectedCount = sockets size
ifTrue: [ done := true ].
(Time millisecondsSince: startTime) >= timeoutMsecs
ifTrue: [ done := true ] ].
result := (sockets select: [ :s | s isConnected ]) collect: [ :s | self nameForWellKnownTCPPort: s remotePort ].
sockets do: [ :s | s destroy ].
^ result
]
{ #category : 'utilities' }
Socket class >> pingPortsOn: hostName [
"Attempt to connect to a set of well-known sockets on the given host, and answer the names of the available ports."
"Socket pingPortsOn: 'pharo.org'"
^ Socket
pingPorts: #(7 13 19 21 23 25 80 110 119)
on: hostName
timeOutSecs: 20
]
{ #category : 'registry' }
Socket class >> register: anObject [
^self registry add: anObject
]
{ #category : 'registry' }
Socket class >> registry [
^ Registry ifNil: [ Registry := FinalizationRegistry new ]
]
{ #category : 'utilities' }
Socket class >> standardTimeout [
^45
]
{ #category : 'instance creation' }
Socket class >> tcpCreateIfFail: failBlock [
"Attempt to create a new socket. If successful, return the new socket. Otherwise, return the result of evaluating the given block. Socket creation can fail if the network isn't available or if there are not sufficient resources available to create another socket."
| sock |
self initializeNetwork.
sock := self newTCP.
sock isValid ifFalse: [^ failBlock value].
^ sock
]
{ #category : 'instance creation' }
Socket class >> udpCreateIfFail: failBlock [
"Attempt to create a new socket. If successful, return the new socket. Otherwise, return the result of evaluating the given block. Socket creation can fail if the network isn't available or if there are not sufficient resources available to create another socket."
| sock |
self initializeNetwork.
sock := self newUDP.
sock isValid ifFalse: [^ failBlock value].
^ sock
]
{ #category : 'registry' }
Socket class >> unregister: anObject [
^self registry remove: anObject ifAbsent:[]
]
{ #category : 'utilities' }
Socket class >> wildcardAddress [
"Answer a don't-care address for use with UDP sockets."
^ByteArray new: 4 "0.0.0.0"
]
{ #category : 'utilities' }
Socket class >> wildcardPort [
"Answer a don't-care port for use with UDP sockets. (The system will allocate an
unused port number to the socket.)"
^0
]
{ #category : 'connection open/close' }
Socket >> accept [
"Accept a connection from the receiver socket.
Return a new socket that is connected to the client"
^Socket acceptFrom: self
]
{ #category : 'initialize - destroy' }
Socket >> acceptFrom: aSocket [
"Initialize a new socket handle from an accept call"
| semaIndex readSemaIndex writeSemaIndex |
socketHandle ifNotNil: [^Error signal: 'The socket is already bound'].
semaphore := Semaphore new.
readSemaphore := Semaphore new.
writeSemaphore := Semaphore new.
semaIndex := Smalltalk registerExternalObject: semaphore.
readSemaIndex := Smalltalk registerExternalObject: readSemaphore.
writeSemaIndex := Smalltalk registerExternalObject: writeSemaphore.
socketHandle := self
primAcceptFrom: aSocket socketHandle
receiveBufferSize: 8000
sendBufSize: 8000
semaIndex: semaIndex
readSemaIndex: readSemaIndex
writeSemaIndex: writeSemaIndex.
socketHandle
ifNil: [
"socket creation failed"
Smalltalk unregisterExternalObject: semaphore.
Smalltalk unregisterExternalObject: readSemaphore.
Smalltalk unregisterExternalObject: writeSemaphore.
readSemaphore := writeSemaphore := semaphore := nil ]
ifNotNil: [ self register ]
]
{ #category : 'accessing' }
Socket >> address [
"Shortcut"
^self localAddress
]
{ #category : 'initialize - destroy' }
Socket >> bindTo: anAddress port: aPort [
"Bind to the local port <aPort>, on the interface specified by <anAddress>
(`SocketAddress zero` specifies all interfaces).
Primarily used to prepare to listen for incoming connections with #listen[WithBacklog:]."
self primSocket: socketHandle bindTo: anAddress port: aPort
]
{ #category : 'initialize - destroy' }
Socket >> bindToPort: aPort [
"Bind to the local port <aPort>, often in order to listen for incoming connections."
self bindTo: SocketAddress zero port: aPort
]
{ #category : 'private - errors' }
Socket >> broadcastError: hostAddress [
^ (NoBroadcastAllowed new
messageText: 'Sending to ' , hostAddress printString , ' without SO_BROADCAST set')
signal
]
{ #category : 'private - errors' }
Socket >> broadcastMisconfiguredForSendingTo: hostAddress [
^ (self isBroadcastAddress: hostAddress)
and: [ ((self getOption: 'SO_BROADCAST') last = 0) ]
]
{ #category : 'connection open/close' }
Socket >> close [
"Close this connection gracefully. For TCP, this sends a close request, but the stream remains open until the other side also closes it."
self primSocketCloseConnection: socketHandle. "close this end"
]
{ #category : 'connection open/close' }
Socket >> closeAndDestroy [
"First, try to close this connection gracefully. If the close attempt fails or times out, abort the connection. In either case, destroy the socket. Do nothing if the socket has already been destroyed (i.e., if its socketHandle is nil)."
self closeAndDestroy: 20
]
{ #category : 'connection open/close' }
Socket >> closeAndDestroy: timeoutSeconds [
"First, try to close this connection gracefully. If the close attempt fails or times out, abort the connection. In either case, destroy the socket. Do nothing if the socket has already been destroyed (i.e., if its socketHandle is nil)."
socketHandle ifNotNil: [
self isConnected ifTrue: [
self close. "close this end"
(self waitForDisconnectionFor: timeoutSeconds) ifFalse: [
"The other end didn't close so we just abort the connection"
self primSocketAbortConnection: socketHandle]].
self destroy]
]
{ #category : 'connection open/close' }
Socket >> connectNonBlockingTo: hostAddress port: port [
"Initiate a connection to the given port at the given host address. This operation will return immediately; follow it with waitForConnectionUntil: to wait until the connection is established."
| status |
self initializeNetwork.
status := self primSocketConnectionStatus: socketHandle.
(status == Unconnected)
ifFalse: [InvalidSocketStatusException signal: 'Socket status must Unconnected before opening a new connection'].
self primSocket: socketHandle connectTo: hostAddress port: port
]
{ #category : 'connection open/close' }
Socket >> connectTo: hostAddress port: port [
"Initiate a connection to the given port at the given host address.
Waits until the connection is established or time outs."
self connectTo: hostAddress port: port waitForConnectionFor: Socket standardTimeout
]
{ #category : 'connection open/close' }
Socket >> connectTo: hostAddress port: port waitForConnectionFor: timeout [
"Initiate a connection to the given port at the given host
address. Waits until the connection is established or time outs."
self connectNonBlockingTo: hostAddress port: port.
self
waitForConnectionFor: timeout
ifClosed: [
ConnectionClosed signal: 'Connection aborted to '
, (NetNameResolver stringFromAddress: hostAddress) , ':'
, port asString ]
ifTimedOut: [
ConnectionTimedOut signal: 'Cannot connect to '
, (NetNameResolver stringFromAddress: hostAddress) , ':'
, port asString ]
]
{ #category : 'connection open/close' }
Socket >> connectToHostNamed: hostName port: portNumber [
| serverIP |
serverIP := NetNameResolver addressForName: hostName timeout: 20.
^self connectTo: serverIP port: portNumber
]
{ #category : 'queries' }
Socket >> dataAvailable [
"Return true if this socket has unread received data."
socketHandle ifNil: [^ false].
^ self primSocketReceiveDataAvailable: socketHandle
]
{ #category : 'initialize - destroy' }
Socket >> destroy [
"Destroy this socket. Its connection, if any, is aborted and its resources are freed.
Any processes waiting on the socket are freed immediately, but it is up to them to
recognize that the socket has been destroyed.
Do nothing if the socket has already been destroyed (i.e., if its socketHandle is nil)."
socketHandle ifNotNil: [
| saveSemaphores |
self isValid ifTrue: [ self primSocketDestroy: socketHandle ].
socketHandle := nil.
Smalltalk unregisterExternalObject: semaphore.
Smalltalk unregisterExternalObject: readSemaphore.
Smalltalk unregisterExternalObject: writeSemaphore.
"Stash the semaphores and nil them before signaling to make sure
no caller gets a chance to wait on them again and block forever."
saveSemaphores := {
semaphore.
readSemaphore.
writeSemaphore }.
semaphore := readSemaphore := writeSemaphore := nil.
"A single #signal should be sufficient, as multiple processes trying to
read or write at once will result in undefined behavior anyway as their
data gets all mixed up together."
saveSemaphores do: [ :each | each signal ].
self unregister ]
]
{ #category : 'receiving' }
Socket >> discardReceivedData [
"Discard any data received up until now, and return the number of bytes discarded."
| buf totalBytesDiscarded |
buf := String new: 10000.
totalBytesDiscarded := 0.
[self isConnected] whileTrue: [
totalBytesDiscarded :=
totalBytesDiscarded + (self receiveDataInto: buf)].
^ totalBytesDiscarded
]
{ #category : 'connection open/close' }
Socket >> disconnect [
"Break this connection, no matter what state it is in. Data that has been sent but not received will be lost."
self primSocketAbortConnection: socketHandle
]
{ #category : 'private - errors' }
Socket >> errorSending: data startingAt: startIndex count: aCount toHost: hostAddress port: portNumber [
"If there are known primitive failure reasons when sending that can be specified using more exact errors, discern them here"
"Only applicable to UDP sockets, TCP does not have broadcast"
(self broadcastMisconfiguredForSendingTo: hostAddress)
ifTrue: [ ^ self broadcastError: hostAddress ].
^ SocketError signal: self socketErrorMessage
]
{ #category : 'finalization' }
Socket >> finalize [
self primSocketDestroyGently: socketHandle.
Smalltalk unregisterExternalObject: semaphore.
Smalltalk unregisterExternalObject: readSemaphore.
Smalltalk unregisterExternalObject: writeSemaphore
]
{ #category : 'other' }
Socket >> getOption: aName [
"Get options on this socket, see Unix man pages for values for
sockets, IP, TCP, UDP. IE SO_KEEPALIVE
returns an array, element one is an status number (0 ok, -1 read only option)
element two is the resulting of the requested option"
(socketHandle == nil or: [self isValid not])
ifTrue: [InvalidSocketStatusException signal: 'Socket status must valid before getting an option'].
^self primSocket: socketHandle getOption: aName
"| foo options |
Socket initializeNetwork.
foo := Socket newTCP.
foo connectTo: (NetNameResolver addressFromString: '192.168.1.1') port: 80.
foo waitForConnectionUntil: (Socket standardDeadline).
options := {
'SO_DEBUG'. 'SO_REUSEADDR'. 'SO_REUSEPORT'. 'SO_DONTROUTE'.
'SO_BROADCAST'. 'SO_SNDBUF'. 'SO_RCVBUF'. 'SO_KEEPALIVE'.
'SO_OOBINLINE'. 'SO_PRIORITY'. 'SO_LINGER'. 'SO_RCVLOWAT'.
'SO_SNDLOWAT'. 'IP_TTL'. 'IP_HDRINCL'. 'IP_RCVOPTS'.
'IP_RCVDSTADDR'. 'IP_MULTICAST_IF'. 'IP_MULTICAST_TTL'.
'IP_MULTICAST_LOOP'. 'UDP_CHECKSUM'. 'TCP_MAXSEG'.
'TCP_NODELAY'. 'TCP_ABORT_THRESHOLD'. 'TCP_CONN_NOTIFY_THRESHOLD'.
'TCP_CONN_ABORT_THRESHOLD'. 'TCP_NOTIFY_THRESHOLD'.
'TCP_URGENT_PTR_TYPE'}.
1 to: options size do: [:i | | fum |
fum :=foo getOption: (options at: i).
Transcript show: (options at: i),fum printString;cr].
foo := Socket newUDP.
foo setPeer: (NetNameResolver addressFromString: '192.168.1.9') port: 7.
foo waitForConnectionUntil: (Socket standardDeadline).
1 to: options size do: [:i | | fum |
fum :=foo getOption: (options at: i).
Transcript show: (options at: i),fum printString;cr].
"
]
{ #category : 'initialization' }
Socket >> initialize: socketType [
"Initialize a new socket handle. If socket creation fails, socketHandle will be set to nil."
| semaIndex readSemaIndex writeSemaIndex |
socketHandle ifNotNil: [^Error signal: 'The socket is already bound'].
semaphore := Semaphore new.
readSemaphore := Semaphore new.
writeSemaphore := Semaphore new.
semaIndex := Smalltalk registerExternalObject: semaphore.
readSemaIndex := Smalltalk registerExternalObject: readSemaphore.
writeSemaIndex := Smalltalk registerExternalObject: writeSemaphore.
socketHandle := self
primSocketCreateNetwork: 0
type: socketType
receiveBufferSize: 8000
sendBufSize: 8000
semaIndex: semaIndex
readSemaIndex: readSemaIndex
writeSemaIndex: writeSemaIndex.
socketHandle
ifNil: [
"socket creation failed"
Smalltalk unregisterExternalObject: semaphore.
Smalltalk unregisterExternalObject: readSemaphore.
Smalltalk unregisterExternalObject: writeSemaphore.
readSemaphore := writeSemaphore := semaphore := nil ]
ifNotNil: [ self register ]
]
{ #category : 'initialize - destroy' }
Socket >> initializeNetwork [
self class initializeNetwork
]
{ #category : 'queries' }
Socket >> isBroadcastAddress: anAddress [
"Only IPv4 has broadcast, in IPv6 all nodes are required to support multicast, and that is used instead."
^ anAddress size = 4 and: [ anAddress last = 255 ]
]
{ #category : 'queries' }
Socket >> isConnected [
"Return true if this socket is connected."
socketHandle ifNil: [ ^ false ].
^ (self primSocketConnectionStatus: socketHandle) == Connected
]
{ #category : 'queries' }
Socket >> isOtherEndClosed [
"Return true if this socket had the other end closed."
socketHandle ifNil: [ ^ false ].
^ (self primSocketConnectionStatus: socketHandle) == OtherEndClosed
]
{ #category : 'queries' }
Socket >> isThisEndClosed [
"Return true if this socket had the this end closed."
socketHandle ifNil: [ ^ false ].
^ (self primSocketConnectionStatus: socketHandle) == ThisEndClosed
]
{ #category : 'queries' }
Socket >> isUnconnected [
"Return true if this socket's state is Unconnected."
socketHandle ifNil: [ ^ false ].
^ (self primSocketConnectionStatus: socketHandle) == Unconnected
]
{ #category : 'queries' }
Socket >> isUnconnectedOrInvalid [
"Return true if this socket is completely disconnected or is invalid."
| status |
socketHandle ifNil: [ ^ true ].
status := self primSocketConnectionStatus: socketHandle.
^ status = Unconnected | (status = InvalidSocket)
]
{ #category : 'queries' }
Socket >> isValid [
"Return true if this socket contains a valid, non-nil socket handle."
| status |
socketHandle ifNil: [ ^ false ].
status := self primSocketConnectionStatus: socketHandle.
^ status ~= InvalidSocket
]
{ #category : 'queries' }
Socket >> isWaitingForConnection [
"Return true if this socket is waiting for a connection."
socketHandle ifNil: [ ^ false ].
^ (self primSocketConnectionStatus: socketHandle) == WaitingForConnection
]
{ #category : 'connection open/close' }
Socket >> listen [
"Listen for a connection (after binding to a port using #bindTo:port:).
If this method succeeds, you must wait for a connection attempt with #waitForConnectionFor:,
then #accept may be used to establish a new connection"
self listenWithBacklog: 1
]
{ #category : 'connection open/close' }
Socket >> listenOn: port [
self
bindToPort: port;
listen
]
{ #category : 'connection open/close' }
Socket >> listenOn: portNumber backlogSize: backlog [
self
bindToPort: portNumber;
listenWithBacklog: backlog
]
{ #category : 'connection open/close' }
Socket >> listenOn: portNumber backlogSize: backlog interface: ifAddr [
self
bindTo: ifAddr port: portNumber;
listenWithBacklog: backlog
]
{ #category : 'connection open/close' }
Socket >> listenWithBacklog: anIntegerBacklog [
"Listen for a connection, allowing <anIntegerBacklog> connections to be queued by the OS.
Must already be bound to a port using #bindTo:port:.
If this method succeeds, you must wait for a connection attempt with #waitForConnectionFor:,
then #accept may be used to establish a new connection"
| status |
status := self primSocketConnectionStatus: socketHandle.
status == Unconnected ifFalse: [
InvalidSocketStatusException signal:
'Socket status must Unconnected before listening for a new connection' ].
self primSocket: socketHandle listenWithBacklog: anIntegerBacklog
]
{ #category : 'accessing' }
Socket >> localAddress [
"If in the process of connecting, wait for connection to be established and binding to address completed before resolving."
^ self retryIfWaitingForConnection: [
self primSocketLocalAddress: socketHandle ]
]
{ #category : 'accessing' }
Socket >> localPort [
"If in the process of connecting, wait for connection to be established and binding to address completed before resolving."
^ self retryIfWaitingForConnection: [
self primSocketLocalPort: socketHandle ]
]
{ #category : 'accessing' }
Socket >> peerName [
"Return the name of the host I'm connected to, or nil if its name isn't known to the domain name server or the request times out."
"Note: Slow. Calls the domain name server, taking up to 20 seconds to time out. Even when sucessful, delays of up to 13 seconds have been observed during periods of high network load."
^ NetNameResolver
nameForAddress: self remoteAddress
timeout: 20
]
{ #category : 'accessing' }
Socket >> port [
"Shortcut"
^self localPort
]
{ #category : 'primitives' }
Socket >> primAcceptFrom: aHandle receiveBufferSize: rcvBufSize sendBufSize: sndBufSize semaIndex: semaIndex [
"Create and return a new socket handle based on accepting the connection from the given listening socket"
<primitive: 'primitiveSocketAccept' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primAcceptFrom: aHandle receiveBufferSize: rcvBufSize sendBufSize: sndBufSize semaIndex: semaIndex readSemaIndex: aReadSema writeSemaIndex: aWriteSema [
"Create and return a new socket handle based on accepting the connection from the given listening socket"
<primitive: 'primitiveSocketAccept3Semaphores' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives - ipv6' }
Socket >> primSocket: socketID bindTo: socketAddress [
<primitive: 'primitiveSocketBindTo' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocket: socketID bindTo: anAddress port: aPort [
"Bind socket to provided IPv4 address and port"
<primitive: 'primitiveSocketBindToPort' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives - ipv6' }
Socket >> primSocket: socketID connectTo: socketAddress [
<primitive: 'primitiveSocketConnectTo' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocket: socketID connectTo: hostAddress port: port [
"Attempt to establish a connection to the given port of the given host. This is an asynchronous call; query the socket status to discover if and when the connection is actually completed."
<primitive: 'primitiveSocketConnectToPort' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocket: socketID getOption: aString [
"Get some option information on this socket. Refer to the UNIX
man pages for valid SO, TCP, IP, UDP options. In case of doubt
refer to the source code.
TCP:=NODELAY, SO:=KEEPALIVE are valid options for example
returns an array containing the error code and the option value"
<primitive: 'primitiveSocketGetOptions' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives - ipv6' }
Socket >> primSocket: socketID listenWithBacklog: backlogSize [
<primitive: 'primitiveSocketListenWithBacklog' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives - ipv6' }
Socket >> primSocket: socketID localAddressResult: socketAddress [
<primitive: 'primitiveSocketLocalAddressResult' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocket: socketID receiveDataInto: aStringOrByteArray startingAt: startIndex count: count [
"Receive data from the given socket into the given array starting at the given index. Return the number of bytes read or zero if no data is available."
<primitive: 'primitiveSocketReceiveDataBufCount' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocket: socketID receiveUDPDataInto: aStringOrByteArray startingAt: startIndex count: count [
"Receive data from the given socket into the given array starting at the given index.
Return an Array containing the amount read, the host address byte array, the host port, and the more flag"
<primitive: 'primitiveSocketReceiveUDPDataBufCount' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives - ipv6' }
Socket >> primSocket: socketID remoteAddressResult: socketAddress [
<primitive: 'primitiveSocketRemoteAddressResult' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocket: socketID sendData: aStringOrByteArray startIndex: startIndex count: count [
"Send data to the remote host through the given socket starting with the given byte index of the given byte array. The data sent is 'pushed' immediately. Return the number of bytes of data actually sent; any remaining data should be re-submitted for sending after the current send operation has completed."
"Note: In general, it many take several sendData calls to transmit a large data array since the data is sent in send-buffer-sized chunks. The size of the send buffer is determined when the socket is created."
<primitive: 'primitiveSocketSendDataBufCount' module: 'SocketPlugin'>
^ self
errorSending: aStringOrByteArray
startingAt: startIndex
count: count
toHost: self remoteAddress
port: self remotePort
]
{ #category : 'primitives' }
Socket >> primSocket: socketID sendUDPData: aStringOrByteArray toHost: hostAddress port: portNumber startIndex: startIndex count: count [
"Send data to the remote host through the given socket starting with the given byte index of the given byte array. The data sent is 'pushed' immediately. Return the number of bytes of data actually sent; any remaining data should be re-submitted for sending after the current send operation has completed."
"Note: In general, it many take several sendData calls to transmit a large data array since the data is sent in send-buffer-sized chunks. The size of the send buffer is determined when the socket is created."
<primitive: 'primitiveSocketSendUDPDataBufCount' module: 'SocketPlugin'>
^ self
errorSending: aStringOrByteArray
startingAt: startIndex
count: count
toHost: hostAddress
port: portNumber
]
{ #category : 'primitives' }
Socket >> primSocket: socketID setOption: aString value: aStringValue [
"Set some option information on this socket. Refer to the UNIX
man pages for valid SO, TCP, IP, UDP options. In case of doubt
refer to the source code.
TCP:=NODELAY, SO:=KEEPALIVE are valid options for example
returns an array containing the error code and the negotiated value"
<primitive: 'primitiveSocketSetOptions' module: 'SocketPlugin'>
^nil
]
{ #category : 'primitives' }
Socket >> primSocket: socketID setPort: port [
"Set the local port associated with a UDP socket.
Note: this primitive is overloaded. The primitive will not fail on a TCP socket, but
the effects will not be what was desired. Best solution would be to split Socket into
two subclasses, TCPSocket and UDPSocket."
<primitive: 'primitiveSocketListenWithOrWithoutBacklog' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocketAbortConnection: socketID [
"Terminate the connection on the given port immediately without going through the normal close sequence. This is an asynchronous call; query the socket status to discover if and when the connection is actually terminated."
<primitive: 'primitiveSocketAbortConnection' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocketCloseConnection: socketID [
"Close the connection on the given port. The remote end is informed that this end has closed and will do no further sends. This is an asynchronous call; query the socket status to discover if and when the connection is actually closed."
<primitive: 'primitiveSocketCloseConnection' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocketConnectionStatus: socketID [
"Return an integer reflecting the connection status of this socket. For a list of possible values, see the comment in the 'initialize' method of this class. If the primitive fails, return a status indicating that the socket handle is no longer valid, perhaps because the Pharo image was saved and restored since the socket was created. (Sockets do not survive snapshots.)"
<primitive: 'primitiveSocketConnectionStatus' module: 'SocketPlugin'>
^ InvalidSocket
]
{ #category : 'primitives' }
Socket >> primSocketCreateNetwork: netType type: socketType receiveBufferSize: rcvBufSize sendBufSize: sendBufSize semaIndex: semaIndex [
"Return a new socket handle for a socket of the given type and buffer sizes. Return nil if socket creation fails.
The netType parameter is platform dependent and can be used to encode both the protocol type (IP, Xerox XNS, etc.) and/or the physical network interface to use if this host is connected to multiple networks. A zero netType means to use IP protocols and the primary (or only) network interface.
The socketType parameter specifies:
0 reliable stream socket (TCP if the protocol is IP)
1 unreliable datagram socket (UDP if the protocol is IP)
The buffer size parameters allow performance to be tuned to the application. For example, a larger receive buffer should be used when the application expects to be receiving large amounts of data, especially from a host that is far away. These values are considered requests only; the underlying implementation will ensure that the buffer sizes actually used are within allowable bounds. Note that memory may be limited, so an application that keeps many sockets open should use smaller buffer sizes. Note the macintosh implementation ignores this buffer size. Also see setOption to get/set socket buffer sizes which allows you to set/get the current buffer sizes for reading and writing.
If semaIndex is > 0, it is taken to be the index of a Semaphore in the external objects array to be associated with this socket. This semaphore will be signalled when the socket status changes, such as when data arrives or a send completes. All processes waiting on the semaphore will be awoken for each such event; each process must then query the socket state to figure out if the conditions they are waiting for have been met. For example, a process waiting to send some data can see if the last send has completed."
<primitive: 'primitiveSocketCreate' module: 'SocketPlugin'>
^ nil "socket creation failed"
]
{ #category : 'primitives' }
Socket >> primSocketCreateNetwork: netType type: socketType receiveBufferSize: rcvBufSize sendBufSize: sendBufSize semaIndex: semaIndex readSemaIndex: aReadSema writeSemaIndex: aWriteSema [
"See comment in primSocketCreateNetwork: with one semaIndex. However you should know that some implementations
ignore the buffer size and this interface supports three semaphores, one for open/close/listen and the other two for
reading and writing"
<primitive: 'primitiveSocketCreate3Semaphores' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocketDestroy: socketID [
"Release the resources associated with this socket. If a connection is open, it is aborted."
<primitive: 'primitiveSocketDestroy' module: 'SocketPlugin'>
^ SocketError signal: self socketErrorMessage
]
{ #category : 'primitives' }
Socket >> primSocketDestroyGently: socketID [
"Release the resources associated with this socket. If a connection is open, it is aborted.
Do not fail if the receiver is already closed."
<primitive: 'primitiveSocketDestroy' module: 'SocketPlugin'>
]