Network-Kernel

ConnectionClosed
Signals a prematurely closed connection.
ConnectionQueue
A ConnectionQueue listens on a given port number and collects a queue of client connections. In order to handle state changes quickly, a ConnectionQueue has its own process that: (a) tries to keep a socket listening on the port whenever the queue isn't already full of connections and (b) prunes stale connections out of the queue to make room for fresh ones.
connectionCount
Return an estimate of the number of currently queued connections. This is only an estimate since a new connection could be made, or an existing one aborted, at any moment.
destroy
Terminate the listener process and destroy all sockets in my possesion.
getConnectionOrNil
Return a connected socket, or nil if no connection has been established.
getConnectionOrNilLenient
Return a connected socket, or nil if no connection has been established.
initPortNumber:queueLength:
Private! Initialize the receiver to listen on the given port number. Up to queueLength connections will be queued.
isValid
listenLoop
Private! This loop is run in a separate process. It will establish up to maxQueueLength connections on the given port.
oldListenLoop
Private! This loop is run in a separate process. It will establish up to maxQueueLength connections on the given port.
oldStyleListenLoop
Private! This loop is run in a separate process. It will establish up to maxQueueLength connections on the given port.
portNumber:queueLength:
pruneStaleConnections
Private! The client may establish a connection and then disconnect while it is still in the connection queue. This method is called periodically to prune such sockets out of the connection queue and make room for fresh connections.
ConnectionRefused
Signals that a connection to the specified host and port was refused.
host host which refused the connection
port prot to which the connection was refused
host
host:port:
port
ConnectionTimedOut
Signals that a connection attempt timed out.
InternetConfiguration
An InternetConfiguration is xxxxxxxxx.
Instance Variables
getArchiePreferred
getDownloadPath
getEmail
getFTPHost
getFTPProxyAccount
getFTPProxyHost
getFTPProxyPassword
getFTPProxyUser
getFingerHost
getGopherHost
getGopherProxy
getHTTPProxyHost
getIRCHost
getLDAPSearchbase
getLDAPServer
getMacintoshFileTypeAndCreatorFrom:
getMailAccount
getMailPassword
getNNTPHost
getNTPHost
getNewsAuthPassword
getNewsAuthUsername
getNoProxyDomains
getOrganization
getPhHost
getRealName
getSMTPHost
getSocksHost
getTelnetHost
getWAISGateway
getWWWHomePage
getWhoisHost
initialize
Subclasses should redefine this method to perform initializations on instance creation
primitiveGetMacintoshFileTypeAndCreatorFrom:
primitiveGetStringKeyedBy:
shutDown
startUp
useFTPProxy
useGopherProxy
useHTTPProxy
usePassiveFTP
useSocks
InvalidSocketStatusException
Signals if an operation on a Socket found it in a state invalid for that operation.
NameLookupFailure
Signals that a name lookup operation failed.
hostName hostName for which the name loopup failed
defaultAction
Backward compatibility
hostName
hostName:
NetNameResolver
This class implements TCP/IP style network name lookup and translation facilities.
Attempt to keep track of whether there is a network available.
HaveNetwork true if last attempt to contact the network was successful.
LastContact Time of that contact (totalSeconds).
haveNetwork returns true, false, or #expired. True means there was contact in the last 30 minutes. False means contact failed or was false last time we asked. Get out of false state by making contact with a server in some way (FileList or updates).
addressForName:
addressForName:timeout:
addressFromString:
addressesForName:
initialize
Subclasses should redefine this method to perform initializations on instance creation
initializeNetwork
localAddressString
localHostAddress
localHostName
nextSocketAddressInformation
oldAddressForName:
primAbortLookup
primAddressLookupResult
primGetAddressInfoFamily
primGetAddressInfoHost:service:flags:family:type:protocol:
primGetAddressInfoNext
primGetAddressInfoProtocol
primGetAddressInfoResult:
primGetAddressInfoSize
primGetAddressInfoType
primGetNameInfo:flags:
primGetNameInfoHostResult:
primGetNameInfoHostSize
primGetNameInfoServiceResult:
primGetNameInfoServiceSize
primHostNameResult:
primHostNameSize
primInitializeNetwork:
primLocalAddress
primNameLookupResult
primNameResolverError
primNameResolverStatus
primStartLookupOfAddress:
primStartLookupOfName:
promptUserForHostAddress
promptUserForHostAddressDefault:
readDecimalByteFrom:
resolverError
resolverMutex
resolverStatus
stringFromAddress:
testIPv6
testIPv6Echo
testPort80
useOldNetwork
waitForCompletionUntil:
waitForResolverReadyUntil:
NetworkError
Abstract super class for all network related exceptions.
NoNetworkError
Signals that no network was found. This could happen, e.g., on dial-up connection when no connection was established when Squeak tried to access it.
Password
"Hold a password. There are three ways to get the password.
If there is no password (sequence == nil), ask the user for it.
If the use supplied one during this session, return that. It is cleared at shutDown.
If sequence is a number, get the server passwords off the disk. File 'sqk.info' must be in the same folder 'Squeak.sources' file. Decode the file. Return the password indexed by sequence."
cache:
decode:
Xor with secret number -- just so file won't have raw password in it
passwordFor:
Returned the password from one of many sources. OK if send in a nil arg.
sequence
sequence:
serverPasswords
Get the server passwords off the disk and decode them. The file 'sqk.info' must be in some folder that Squeak thinks is special (vm folder, or default directory). (Note: This code works even if you are running with no system sources file.)
shutDown
Socket
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 Squeak 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.
accept
Accept a connection from the receiver socket.
Return a new socket that is connected to the client
acceptFrom:
Initialize a new socket handle from an accept call
address
Shortcut
bindTo:
close
Close this connection gracefully. For TCP, this sends a close request, but the stream remains open until the other side also closes it.
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).
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).
connectNonBlockingTo:
connectNonBlockingTo: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.
connectTo:
connectTo:port:
Initiate a connection to the given port at the given host address.
Waits until the connection is established or time outs.
connectTo:port:waitForConnectionFor:
Initiate a connection to the given port at the given host
address. Waits until the connection is established or time outs.
connectTo:waitForConnectionFor:
connectToHostNamed:port:
createIfFail:
dataAvailable
Return true if this socket has unread received data.
deadServer
deadServer:
deadlineSecs:
destroy
Destroy this socket. Its connection, if any, is aborted and its resources are freed. Do nothing if the socket has already been destroyed (i.e., if its socketHandle is nil).
discardReceivedData
Discard any data received up until now, and return the number of bytes discarded.
disconnect
Break this connection, no matter what state it is in. Data that has been sent but not received will be lost.
finalize
Finalize the resource associated with the receiver. This message should only be sent during the finalization process. There is NO garantuee that the resource associated with the receiver hasn't been free'd before so take care that you don't run into trouble - this all may happen with interrupt priority.
getOption:
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
initialize
Subclasses should redefine this method to perform initializations on instance creation
initialize:
Initialize a new socket handle. If socket creation fails, socketHandle will be set to nil.
initialize:family:
Initialize a new socket handle. If socket creation fails, socketHandle will be set to nil.
initializeNetwork
isConnected
Return true if this socket is connected.
isOtherEndClosed
Return true if this socket had the other end closed.
isThisEndClosed
Return true if this socket had the this end closed.
isUnconnected
Return true if this socket's state is Unconnected.
isUnconnectedOrInvalid
Return true if this socket is completely disconnected or is invalid.
isValid
Return true if this socket contains a valid, non-nil socket handle.
isWaitingForConnection
Return true if this socket is waiting for a connection.
listenOn:
Listen for a connection on the given port. This operation will return immediately; follow it with waitForConnectionUntil: to wait until a connection is established.
listenOn:backlogSize:
Listen for a connection on the given port.
If this method succeeds, #accept may be used to establish a new connection
listenOn:backlogSize:interface:
Listen for a connection on the given port.
If this method succeeds, #accept may be used to establish a new connection
listenWithBacklog:
localAddress
localPort
localSocketAddress
loopbackTest
nameForWellKnownTCPPort:
new
newAcceptCheck
newTCP
newTCP:
newUDP
newUDP:
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.
ping:
pingPorts:on:timeOutSecs:
pingPortsOn:
port
Shortcut
primAcceptFrom:receiveBufferSize:sendBufSize:semaIndex:
Create and return a new socket handle based on accepting the connection from the given listening socket
primAcceptFrom:receiveBufferSize:sendBufSize:semaIndex:readSemaIndex:writeSemaIndex:
Create and return a new socket handle based on accepting the connection from the given listening socket
primInitializeNetwork:
primSocket:bindTo:
primSocket:connectTo:
primSocket:connectTo: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.
primSocket:getOption:
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
primSocket:listenOn:
Listen for a connection on the given port. This is an asynchronous call; query the socket status to discover if and when the connection is actually completed.
primSocket:listenOn:backlogSize:
Primitive. Set up the socket to listen on the given port.
Will be used in conjunction with #accept only.
primSocket:listenOn:backlogSize:interface:
Primitive. Set up the socket to listen on the given port.
Will be used in conjunction with #accept only.
primSocket:listenWithBacklog:
primSocket:localAddressResult:
primSocket:receiveDataInto:startingAt: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.
primSocket:receiveUDPDataInto:startingAt: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
primSocket:remoteAddressResult:
primSocket:sendData:startIndex: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.
primSocket:sendUDPData:toHost:port:startIndex: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.
primSocket:setOption:value:
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
primSocket:setPort:
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.
primSocketAbortConnection:
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.
primSocketCloseConnection:
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.
primSocketConnectionStatus:
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 Squeak image was saved and restored since the socket was created. (Sockets do not survive snapshots.)
primSocketCreateNetwork:type:receiveBufferSize:sendBufSize: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.
primSocketCreateNetwork:type:receiveBufferSize:sendBufSize:semaIndex:readSemaIndex:writeSemaIndex:
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
primSocketDestroy:
Release the resources associated with this socket. If a connection is open, it is aborted.
primSocketDestroyGently:
Release the resources associated with this socket. If a connection is open, it is aborted.
Do not fail if the receiver is already closed.
primSocketError:
Return an integer encoding the most recent error on this socket. Zero means no error.
primSocketLocalAddress:
Return the local host address for this socket.
primSocketLocalAddressSize:
primSocketLocalPort:
Return the local port for this socket, or zero if no port has yet been assigned.
primSocketReceiveDataAvailable:
Return true if data may be available for reading from the current socket.
primSocketRemoteAddress:
Return the remote host address for this socket, or zero if no connection has been made.
primSocketRemoteAddressSize:
primSocketRemotePort:
Return the remote port for this socket, or zero if no connection has been made.
primSocketSendDone:
Return true if there is no send in progress on the current socket.
primitiveOnlySupportsOneSemaphore
printOn:
Append to the argument, aStream, a sequence of characters that
identifies the receiver.
pushData:
Send aStringOrByteArray to the remote host trough the given socket. Push the data immediately and ignore all kinds of errors. Return true if all the data could be sent successfully, in case of problems return false and destroy the socket.
readSemaphore
receiveAvailableData
Receive all available data (if any). Do not wait.
receiveAvailableDataInto:
Receive all available data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Do not wait for data.
receiveAvailableDataInto:startingAt:
Receive all available data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Do not wait for data.
receiveAvailableDataIntoBuffer:
Receive all available data (if any). Do not wait.
receiveData
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Waits for data once.
Either returns data or signals a time out or connection close.
receiveDataInto:
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Waits for data once.
Either returns data or signals a time out or connection close.
receiveDataInto:fromHost:port:
Receive a UDP packet from the given hostAddress/portNumber, storing the data in the given buffer, and return the number of bytes received. Note the given buffer may be only partially filled by the received data.
receiveDataInto:startingAt:
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Waits for data once. The answer may be zero (indicating that no data was
available before the socket closed).
receiveDataSignallingClosedInto:startingAt:
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Waits for data until something is read or the socket is closed, upon which
we signal.
receiveDataSignallingTimeout:into:startingAt:
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Wait for data once for the specified nr of seconds. This method will
throw exceptions on timeout or the socket closing.
receiveDataTimeout:
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Waits for data once.
receiveDataTimeout:into:
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Waits for data once.
receiveDataTimeout:into:startingAt:
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Wait for data once for the specified nr of seconds. The answer may be
zero (indicating that there was no data available within the given timeout).
receiveDataWithTimeout
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Waits for data once.
Either returns data or signals a time out or connection close.
receiveDataWithTimeoutInto:
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Waits for data once.
Either returns data or signals a time out or connection close.
receiveDataWithTimeoutInto:startingAt:
Receive data into the given buffer and return the number of bytes received.
Note the given buffer may be only partially filled by the received data.
Waits for data once.
receiveSomeData
Receive currently available data (if any). Do not wait.
receiveSomeDataInto:
Receive data into the given buffer and return the number of bytes received. Note the given buffer may be only partially filled by the received data.
receiveSomeDataInto:startingAt:
Receive data into the given buffer and return the number of bytes received. Note the given buffer may be only partially filled by the received data.
receiveUDPDataInto:
Receive UDP data into the given buffer and return the number of bytes received. Note the given buffer may be only partially filled by the received data. What is returned is an array, the first element is the bytes read, the second the sending bytearray address, the third the senders port, the fourth, true if more of the datagram awaits reading
register
register:
registry
registryThreshold
registryThreshold:
remoteAddress
remotePort
remoteSocketAddress
semaphore
sendCommand:
Send the given command as a single line followed by a <CR><LF> terminator.
sendData:
Send all of the data in the given array, even if it requires multiple calls to send it all. Return the number of bytes sent.
sendData:count:
Send the amount of data from the given buffer
sendData:toHost:port:
Send a UDP packet containing the given data to the specified host/port.
sendDone
Return true if the most recent send operation on this socket has completed.
sendSomeData:
Send as much of the given data as possible and answer the number of bytes actually sent.
sendSomeData:startIndex:
Send as much of the given data as possible starting at the given index. Answer the number of bytes actually sent.
sendSomeData:startIndex:count:
Send up to count bytes of the given data starting at the given index. Answer the number of bytes actually sent.
sendStreamContents:
Send the data in the stream. Close the stream.
Usefull for directly sending contents of a file without reading into memory first.
sendStreamContents:checkBlock:
Send the data in the stream. Close the stream after you are done. After each block of data evaluate checkBlock and abort if it returns false.
Usefull for directly sending contents of a file without reading into memory first.
sendTest
sendUDPData:toHost:port:
Send a UDP packet containing the given data to the specified host/port.
setOption:value:
setup options on this socket, see Unix man pages for values for
sockets, IP, TCP, UDP. IE SO:=KEEPALIVE
returns an array, element one is the error number
element two is the resulting of the negotiated value.
See getOption for list of keys
setPeer:port:
Set the default send/recv address.
setPort:
Associate a local port number with a UDP socket. Not applicable to TCP sockets.
socketError
socketHandle
standardDeadline
standardTimeout
statusString
Return a string describing the status of this socket.
tcpCreateIfFail:
timeTest
timeTestUDP
udpCreateIfFail:
unregister
unregister:
waitForAcceptFor:
Wait and accept an incoming connection. Return nil if it falis
waitForAcceptFor:ifTimedOut:
Wait and accept an incoming connection
waitForAcceptUntil:
Wait and accept an incoming connection
waitForConnectionFor:
Wait up until the given deadline for a connection to be established. Return true if it is established by the deadline, false if not.
waitForConnectionFor:ifTimedOut:
Wait up until the given deadline for a connection to be established. Return true if it is established by the deadline, false if not.
waitForConnectionUntil:
Wait up until the given deadline for a connection to be established. Return true if it is established by the deadline, false if not.
waitForConnectionUntil:ifTimedOut:
Wait up until the given deadline for a connection to be established. Return true if it is established by the deadline, false if not.
waitForData
Wait for data to arrive. This method will block until
data is available or the socket is closed. If the socket is closed
a ConnectionClosed exception will be signaled.
waitForDataFor:
Wait for the given nr of seconds for data to arrive.
Signal a time out or connection close exception if either happens before data becomes available.
waitForDataFor:ifClosed:ifTimedOut:
Wait for the given nr of seconds for data to arrive.
waitForDataIfClosed:
Wait indefinitely for data to arrive. This method will block until
data is available or the socket is closed.
waitForDataUntil:
Wait up until the given deadline for data to arrive. Return true if data arrives by the deadline, false if not.
waitForDataUntil:ifClosed:ifTimedOut:
Wait for the given nr of seconds for data to arrive.
waitForDisconnectionFor:
Wait for the given nr of seconds for the connection to be broken.
Return true if it is broken by the deadline, false if not.
The client should know the connection is really going to be closed
(e.g., because he has called 'close' to send a close request to the other end)
before calling this method.
waitForDisconnectionUntil:
Wait for the given nr of seconds for the connection to be broken.
Return true if it is broken by the deadline, false if not.
The client should know the connection is really going to be closed
(e.g., because he has called 'close' to send a close request to the other end)
before calling this method.
waitForSendDoneFor:
Wait up until the given deadline for the current send operation to complete. Return true if it completes by the deadline, false if not.
waitForSendDoneUntil:
Wait up until the given deadline for the current send operation to complete. Return true if it completes by the deadline, false if not.
wildcardAddress
wildcardPort
writeSemaphore
SocketAddress
I represent a socket (network) address consisting of a host internet address and a port number. My contents are opaque and cannot be interpreted directly. See the accessing protocol for methods that retrieve the information I contain.
asSocketAddress
fromOldByteAddress:
hostName
hostNumber
loopback4
loopback6
loopbacks
loopbacks4
loopbacks6
port
port:
printOn:
Append a sequence of characters that identify the receiver to aStream.
serviceName
serviceNumber
wildcard4
wildcard6
wildcards
wildcards4
wildcards6
SocketAddressInformation
I represent a local or remote network service.
Instance Variables
addressFamily: <SmallInteger> the address family (unix, inet4, inet6, ...) in which the service address is available.
protocol: <SmallInteger> the protocol (tcp, udp, ...) that the service uses.
socketAddress: <SocketAddress> the socket address at which the service can be contacted or created.
socketType: <SmallInteger> the type (stream, dgram) of the socket that should be created for communication with the service.
addressFamilyINET4
addressFamilyINET6
addressFamilyLocal
addressFamilyName
addressFamilyUnspecified
connect
forHost:service:flags:addressFamily:socketType:protocol:
initSocketAddress:family:type:protocol:
initialize
Subclasses should redefine this method to perform initializations on instance creation
listenWithBacklog:
numericFlag
passiveFlag
printOn:
Append to the argument, aStream, a sequence of characters that
identifies the receiver.
protocolName
protocolTCP
protocolUDP
protocolUnspecified
socketAddress
socketTypeDGram
socketTypeName
socketTypeStream
socketTypeUnspecified
withSocketAddress:family:type:protocol:
SocketStream
SocketStream is a wrapper for class Socket making it easy to write networking code by giving the programmer a stream-like protocol. A Socket is a two way communication link with two logically separate channels - input and output. The Socket class is the lowest level in Squeak for network communication and using it directly can be difficult and bug prone.
A SocketStream can be in binary or ascii mode, ascii is the default which means you are transmitting and receiving Strings. Most Internet protocols are in clear text ascii, like for example HTTP. Another setting is what timeout you want to use - default is the standardTimeout from Socket. More settings can be found in the method category 'configuration'.
Simplest example of connecting, sending/receiving and closing:
| stream result |
stream := SocketStream openConnectionToHostNamed: 'www.squeak.org' port: 80.
[[stream nextPutAll: 'GET / HTTP/1.0'; crlf; crlf; flush.
result := stream upToEnd. "Give us all data until the socket is closed."
Transcript show: result; cr.]
ensure: [stream close]]
on: ConnectionTimedOut
do: [:ex | Transcript show: ex asString;cr. ex resume]
There are two important things to note above:
- The methods in category "stream in" can signal two exceptions (unless turned off with #shouldSignal:):
ConnectionClosed and ConnectionTimedOut
- We close the stream using #ensure:, that is to make sure it isn't left opened.
- We use #on:do: to catch any signal. In this case we do not need to catch ConnectionClosed since #upToEnd does that for us intrinsically.
----------------
SocketStream (below called SS) is a reimplementation of 'Old'-SocketStream (below called OSS) - the class that originates from the original Comanche implementation but now is included in standard Squeak. SS has the same protocol as OSS and is meant to replace it. SS is faster, more flexible, is better documented and adds a few features:
1. #shouldSignal:, which decides if SS should signal low level Socket exceptions (true) or if it should swallow them like original OSS did. Default is true. The only reason I added this is for backwards compatibility - not signalling causes problems - see bug 4 below.
2. #nextAllInBuffer, #nextInBuffer:, #skip:, #receiveData:, #nextPutAllFlush: and #recentlyRead are new additions to the public protocol.
It also fixes various bugs:
1. #isDataAvailable could theoretically answer false, when there actually is some in the buffer in OSS. If #receiveDataIfAvailable reads the last byte then the following "socket dataAvailable" would answer false. So the last byte would be sitting in the inStream missed.
2. #upToAll: in OSS has several problems, for example - #positionOfSubCollection:ifAbsent: which was introduced answers one position too low. This was compensated in upToAll:, but only in the pushBack: call, not the actual result being returned which was cut short 1 byte. Amusingly this makes KomHttpServer not use "Keep-Alive" since the last $e in 'Alive' was cut short. :)
3. SS doesn't inherit from PositionableStream since that just breaks various inherited messages, like for example #skip:. OSS should IMHO be changed to inherit from Object - or of course, replaced in full with SS. :)
4. Since SocketStream by default signals closes and timeouts the SocketStreamTest now passes. The reason for SocketStream to fail is that while it does timeout on a low level (#SocketStream>>receiveData doesn't hang forever) - the callers of #receiveData sometimes loop - like in #next:, and thus eliminates the timeout. SS warns about some methods (in their method comments) not honouring timeouts if shouldSignal is false, I really don't know what they should do in that case:
#next:, #upTo:, #upToAll: and #upToEnd (and #receiveData:)
The primary reason for the SS implementation is optimal performance. The main differences in implementation with the old OSS are:
1. SS uses two buffers directly (inBuffer and outBuffer) with pointers marking start and stop within the buffer. OSS instead uses two regular streams, a ReadStream and a WriteStream. Using internal buffers makes it possible to avoid copying and reallocation in various ways, it also makes SS be able to have specialized growing/buffer moving behaviour.
2. #upTo:, #upToAll: and #peekForAll: uses selectged String messages that in turn uses fast primitives for searching. OSS used other messages that fell back on byte per byte reading.
3. #receiveData in OSS creates a temporary buffer stream for each call! During a long read operation, like say #upToAll: (which for example is used when uploading files using HTTP POST forms), this is devastating - especially since the default size is only 2000 bytes - and leads to a very high number of low level read operations on the Socket, typically 100 times more calls than with OSS. The buffer in OSS is held in an instvar (not recreated for each call), is larger from the start and above all - grows dynamically by doubling. OSS can also avoid a grow/reallocation by doing a "move down" if data has been read from the SS as it comes in and through that making room in the lower part of the inBuffer. The net result is that upToAll: for large files is about 10 times faster.
4. The implementation of upTo: and upToAll: tries to avoid doing unnecessary find operations in the buffer and is greedy by default, which means it favors reading more data - if available - before searching for the stop sequence. If we had #findString:startingAt:stoppingAt: this wouldn't have to be greedy and we wouldn't be needlessly scanning dead buffer area. VM hackers? Also, while you are at it - make it work for ByteArrays too. :)
SS can not be run unbuffered, since that seems unneeded. The option to autoFlush is still available, with it set to true SocketStream (just like OSS) will flush on its own on each nextPut:/nextPutAll:, otherwise flushing it will have to be done manually but is done on close.
The first performance tests shows that, as noted above, receiving large amounts of data using #upToAll: is greatly improved - factor of 10. Serving HTTP with small payloads seemed at first not be faster at all - but this is due to the high overhead of Socket connect/close and other things. Increasing payloads show a difference and especially with keep alive on - where the new SS roughly doubles the throughput!
<<
adjustInBuffer:
Adjust markers and possibly grow inBuffer or move data down.
Currently grows through doubling when less than 1024 bytes are left.
Never shrinks. Returns the position in the buffer where any new
data can be found.
adjustOutBuffer:
Possibly grow outBuffer to accommodate the new data.
Currently grows through doubling when less
than 1024 bytes are left. If bytesToWrite is even
larger we double that instead. Never shrinks.
ascii
Tell the SocketStream to send data
as Strings instead of ByteArrays.
This is default.
atEnd
There is nothing more to read when
there is no more data in our inBuffer, the socket
is disconnected and there is none available on the socket.
Note that we need to check isConnected before isDataAvailable,
otherwise data may sneak in in the meantime. But we check the
buffer first, because it is faster.
autoFlush
If autoFlush is enabled data will be sent through
the socket (flushed) when the bufferSize is reached
or the SocketStream is closed. Otherwise the user
will have to send #flush manually.
Close will always flush. Default is false.
autoFlush:
If autoFlush is enabled data will be sent through
the socket (flushed) when the bufferSize is reached
or the SocketStream is closed. Otherwise the user
will have to send #flush manually.
Close will always flush. Default is false.
binary
Tell the SocketStream to send data
as ByteArrays instead of Strings.
Default is ascii.
bufferSize
Default buffer size is 4kb.
increased from earlier 2000 bytes.
bufferSize:
Default buffer size is 4kb.
increased from earlier 2000 bytes.
checkFlush
If autoFlush is true we flush if
we have reached the bufferSize
of data in the outBuffer.
close
Flush any data still not sent
and take care of the socket.
cr
crlf
debug
Display debug info.
finger:
flush
If the other end is connected and we have something
to send, then we send it and reset the outBuffer.
growInBuffer
Grows through doubling.
ifStale:
inBufferSize
Answers the current size of data in the inBuffer.
initialize
Subclasses should redefine this method to perform initializations on instance creation
isBinary
isConnected
The stream is connected if the socket is.
isDataAvailable
It the inbuffer is empty, we check the socket for data.
If it claims to have data available to read, we try to read
some once and recursively call this method again.
If something really was available it is now in the inBuffer.
This is because there has been spurious
dataAvailable when there really is no data to get.
isEmpty
Test if there are more data to read.
isInBufferEmpty
Any data in the buffer?
isOtherEndConnected
isStream
Return true if the receiver responds to the stream protocol
moveInBufferDown
Move down contents of inBuffer to the start.
Return distance moved.
next
Return next byte, if inBuffer is empty
we recieve some more data and try again.
next:
Answer anInteger bytes of data.
NOTE: This method doesn't honor timeouts if shouldSignal is false!
nextAllInBuffer
Return all data currently in the inBuffer,
nextAvailable
Answer all the data currently available,
in buffer or in socket.
nextAvailable:
Answer all the data currently available,
in buffer or in socket - but limited to <howMany>.
nextInBuffer:
Answer anInteger bytes of data at most,
but only from the inBuffer.
nextLine
nextLineCrLf
nextLineLf
nextPut:
Put a single Character or byte onto the stream.
nextPutAll:
Put a String or a ByteArray onto the stream.
Currently a large collection will allocate a large buffer.
nextPutAllFlush:
Put a String or a ByteArray onto the stream.
You can use this if you have very large data - it avoids
copying into the buffer (and avoids buffer growing)
and also flushes any other pending data first.
noTimeout
Do not use timeout.
on:
openConnectionToHost:port:
openConnectionToHostNamed:port:
outBufferSize
Answers the current size of data in the outBuffer.
peek
Return next byte, if inBuffer is empty
we recieve some more data and try again.
Do not consume the byte.
peek:
Answer anInteger bytes of data.
Do not consume data.
NOTE: This method doesn't honor timeouts if shouldSignal is false!
peekFor:
Read and return next character or byte
if it is equal to the argument.
Otherwise return false.
peekForAll:
Answer whether or not the next string of characters in the receiver
matches aString. If a match is made, advance over that string in the receiver and
answer true. If no match, then leave the receiver alone and answer false.
We use findString:startingAt: to avoid copying.
NOTE: This method doesn't honor timeouts if shouldSignal is false!
print:
printOn:
Display buffer sizes.
receiveAvailableData
Receive available data (as much as fits in the inBuffer)
but not waiting for more to arrive.
Return the position in the buffer where the
new data starts, regardless if anything
was read, see #adjustInBuffer.
receiveData
Receive data with timeout if it has been set.
If shouldSignal is false we use the Socket methods
that swallow those Exceptions, if it is true the
caller will have to handle those Exceptions.
Return the position in the buffer where the
new data starts, regardless if anything
was read, see #adjustInBuffer.
receiveData:
Keep reading the socket until we have nBytes
in the inBuffer or we reach the end. This method
does not return data, but can be used to make sure
data has been read into the buffer from the Socket
before actually reading it from the FastSocketStream.
Mainly used internally. We could also adjust the buffer
to the expected amount of data and avoiding several
incremental grow operations.
NOTE: This method doesn't honor timeouts if shouldSignal
is false! And frankly, I am not sure how to handle that
case or if I care - I think we should always signal.
receiveDataIfAvailable
Only used to check that there really is data to read
from the socket after it signals dataAvailable.
It has been known to signal true and then still
not have anything to read. See also isDataAvailable.
Return the position in the buffer where the
new data starts, regardless if anything
was read, see #adjustInBuffer.
recentlyRead
Return the number of bytes read
during the last socket operation.
resetBuffers
Recreate the buffers with default start sizes.
resizeInBuffer:
Resize the inBuffer by recreating it.
This also has the effect of getting rid of
dead data above inNextToWrite.
<newSize> must >= inBuffer size!
sendCommand:
Sends a String ending it with CR LF and then flush
causing it to block until sent.
shouldSignal
If shouldSignal is enabled the Socket Exceptions
ConnectionClosed and ConnectionTimedOut
will not be swallowed. Default is true.
For more info, see #shouldSignal:
shouldSignal:
If shouldSignal is enabled the Socket Exceptions
ConnectionClosed and ConnectionTimedOut will not be swallowed.
Default is true. And please - don't set it to false - it is better to
use an exception handler (see below) and several methods
in this class will not honour timeouts (says so in their method comments).
Also, it is quite hard to understand what for example #upToEnd
should return to indicate a timeout.

Wrap your use of SocketStream with a handler like:

[stuff := mySocketStream next: 10]
on: ConnectionClosed, ConnectionTimedOut
do: [:ex |
Transcript show: 'Oops! Did not get my ten bytes!;cr]
shouldTimeout
skip:
Skip a number of bytes.
This is faster than #next: since it does not
have to copy and return a new String or ByteArray.
NOTE: This method doesn't honor timeouts if shouldSignal is false!
socket
socket:
space
streamBuffer:
Create a buffer of the correct class and given size.
timeout
Lazily initialized unless it has been set explicitly.
timeout:
upTo:
Return data up to, but not including given character or byte.

NOTE: Does not honour timeouts if shouldSignal is false!

This method looks a bit complicated, and this is mainly because there is no fast search method
in String that takes a stoppingAt: argument. This means we need to ignore getting hits in the
dead buffer area above inNextToWrite.
Another measure is that this implementation is greedy and will load data into the buffer
until there is nothing more available, or it has loaded 100kb - and not until then we search the buffer.
A totally non greedy variant would search on every loop.
upToAll:
Answer a subcollection from the current access position to the occurrence (if any, but not
inclusive) of aStringOrByteArray. If aCollection is not in the stream, answer the entire rest of
the stream.

NOTE: Does not honour timeouts if shouldSignal is false!

This method looks a bit complicated, and this is mainly because there is no fast search method
in String that takes a stoppingAt: argument. This means we need to ignore getting hits in the
dead buffer area above inNextToWrite.
Another measure is that this implementation is greedy and will load data into the buffer
until there is nothing more available, or it has loaded 100kb - and not until then we search the buffer.
A totally non greedy variant would search on every loop.
upToAll:bufferSize:do:
A variant of #upToAll: that executes a block chunk wise for the result instead of
returning the result as a collection. See #upToAll: for details.
upToEnd
Answer all data coming in on the socket until the socket
is closed by the other end, or we get a timeout.
This means this method catches ConnectionClosed by itself.

NOTE: Does not honour timeouts if shouldSignal is false!
SocksSocket
This class implements the socks 4 and partially socks 5 connection protocol.
For backward compatibility the socks protocol is disabled by default, so subclasses still work.
For further documentation check out:
Socks4: http://spiderman.socks.nec.com/protocol/socks4.protocol
Socks5: http://spiderman.socks.nec.com/rfc/rfc1928.txt
connectCommandCode
connectSocks4
connectSocks5
connectTo:port:
Initiate a connection to the given port at the given host address.
Waits until the connection is established or time outs.
connectToHostNamed:port:
defaultSocksHostAddress
defaultSocksPort
defaultSocksVersion
defaultSocksVersion:
defaultTimeOutDuration
dstIP
dstPort
hostIP6Code
hostIPCode
noAutorizationMethod
qualifiedHostNameCode
requestGrantedCode
sendSocks4ConnectionRequestUserId:
The client connects to the SOCKS server and sends a CONNECT request when
it wants to establish a connection to an application server. The client
includes in the request packet the IP address and the port number of the
destination host, and userid, in the following format.
+----+----+----+----+----+----+----+----+----+----+....+----+
| VN | CD | DSTPORT | DSTIP | USERID |NULL|
+----+----+----+----+----+----+----+----+----+----+....+----+
1 1 2 4 variable 1
sendSocks5ConnectionRequest
Once the method-dependent subnegotiation has completed, the client
sends the request details.
shouldUseSocks
skipQualifiedHostName
socks4
socks5
socks5MethodSelection
The client connects to the server, and sends a version
identifier/method selection message.
The server selects from one of the methods given in METHODS, and
sends a METHOD selection message.
socks5RequestReply
socksError:
waitForReply:for:
waitForSocks4ConnectionReply