The Socket Package offers a small set of built-ins enabling access to network socket connections through OScript. Server-style sockets which listen for incoming connection requests may even be implemented. The Socket built-ins are extremely easy to use once understood

The major functionalities offered by the Socket package are the following:

  • Create() to create a Socket.
  • Listen() to make a Socket to listen for inbound connections on a particular port.
  • Connect() to forge an outbound connection to a host at some port, or Accept() to accept an inbound connection request.
  • Read(), ReadBytes(), and Write(), to transfer data across the socket, or StreamUntil() and StreamBytesUntil() to read from a stream socket.
  • Flush() to flush a Socket.
  • Close() to close a Socket.
  • GetAddrByName() to resolve a host IP address by name.
  • CompareIpAddresses() to compare two IP addresses.
  • Here is a short example which makes a request for the OpenText web page http://www.opentext.com/index.html:

    Socket	sock = Socket.Create()
    Integer	nlines = 0
    String	result
    
    Socket.Connect( sock, "www.opentext.com", 80 )
    Socket.Write( sock, "GET /index.html HTTP/1.0" )
    Socket.Write( sock, Web.CRLF )
    Socket.Write( sock, Web.CRLF )
    Socket.Flush( sock )
    
    while ( !IsError( result = Socket.Read( sock ) ) )
    	Echo( result )
    	nlines += 1
    end
    
    Socket.Close( sock )
    
    Echo( "--Done. Read ", nlines, " lines." )

    The output for the example on one run was (truncated):

    HTTP/1.1 200 OK
    Date: Sat, 31 Oct 1998 01:35:13 GMT
    Server: Apache/1.3.2 (Unix)
    Last-Modified: Thu, 29 Oct 1998 18:55:13 GMT
    ETag: "425e-3e0c-3638ba11"
    Accept-Ranges: bytes
    Content-Length: 15884
    Connection: close
    Content-Type: text/html
    
    <HTML>
    <HEAD>
    
    <TITLE>Welcome to Open Text</TITLE>
    
    [...]
    
    </BODY>
    </HTML>
    Done. Read 137 lines.
    

    Here is a short example of a server socket which echoes what is initially read back across the connection.

    Function void Server()
    	Integer port = 2326					// Port to listen on
    	Boolean status = False				// True upon request Accept()
    	Boolean	dataread = False			// True when data read
    	Socket  server = Socket.Create()	// Listening server socket
    	Socket	request = Socket.Create()	// Accepted request socket.
    	Integer	ticks = Date.Tick()			// Time Listen() started
    	Integer	maxwait = 10				// Max seconds to listen
    
    	String s
    
    
    	Socket.Listen( server, port )
    
    	Echo( "Socket waiting for Accept() on port ", port, "..." )
    
    	// Listen for a limited amount of time (maxwait seconds).
    	while ( !status && ( Date.Tick() - ticks < maxwait * 1000 ) )
    
    		status = Socket.Accept( request, server )
    	end
    
    	// Was a request was made and accepted?
    	if ( !status )
    		// No, the listen timed-out
    		Echo( "Listen time-out after ", maxwait, " seconds." )
    	else
    		// Yes, a request was accepted.
    		Echo( "Reading..." )
    
    		// Read input waiting on the socket.
    		while ( !IsError( s = Socket.Read( request ) ) )
    
    			if ( Length( s ) <= 0 )
    				if ( !dataread )
    					// The socket is not ready for reading.
    					// Wait for input.
    				else
    					// The input is exhausted.  Done reading.
    					break
    				end
    			else
    				Echo( 'Read "', s, '"' )
    
    				// Echo the read input back to sender.
    				Socket.Write( request, s )
    
    				dataread = True
    			end
    		end
    
    		// Close the connection request acceptance socket.
    		Socket.Close( request )
    		Echo( "Done." )
    	end
    
    	Echo( "Closing Server." )
    	Socket.Close( server )
    end

    Test the example by executing the script and pointing a web browser at your new server at "http://localhost:2222/index.html". The output of the example was the following for one run, and the Read "GET /index.html ..." portion should appear in the window of your browser as well:

    Socket waiting for Accept() on port 2326...
    Reading...
    Read "GET /index.html HTTP/1.0
    Connection: Keep-Alive
    User-Agent: Mozilla/4.05 [en] (WinNT; I)
    Host: localhost:3335
    Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*
    Accept-Language: en
    Accept-Charset: iso-8859-1,*,utf-8
    
    "
    Done.
    Closing Server.


    Class Attributes Index

     o ConnectRequest
    The callback constant indicating a connection has been made. For internal use only.
     o E_BufferTooSmall
    An Error caused by too small a buffer used during a read.
     o E_EndOfFile
    An Error caused due to end of file during a read.
     o E_Error
    A generic Socket Error.
     o E_UserCancelled
    An Error caused by the user canceling the socket read or write.
     o ReadReady
    The callback constant indicating a connection has been accepted and is now ready for reading. For internal use only.
     o kSecurityNone
    Security constant indicating no security.
     o kSecuritySSL2
    Security constant indicating SSL2 security.
     o kSecuritySSL3
    Security constant indicating SSL3 security.

    Instance Attributes Index

     o pBlocking
    True if block on input.
     o pPeerIPAddress
    The String IP address of the connection, if connected, Undefined otherwise.
     o pPeerPort
    The Integer Port of the connection, if connected, Undefined otherwise.
     o pReadTimeout
    The Socket read timeout in milliseconds.
     o pSecurity
    The security layer used by the Socket.
     o pStreaming
    True if the Socket should behave like a stream.

    Class Methods Index

     o Accept( Socket accept, Socket request )
    Accepts a connection request.
     o Close( Socket sock )
    Closes and flushes the specified Socket.
     o CompareIpAddresses( String addr1, String addr2 )
    Compares two IPv4 or IPv6 addresses.
     o Connect( Socket sock, String host, Integer port )
    Connects a socket to a host and port.
     o Create( [Dynamic featurename], [Dynamic callbackobj] )
    Creates a new Socket.
     o Flush( Socket sock )
    Flushes the output buffer of a Socket.
     o GetAddrByName( String hostname )
    Gets the address of the specfied host.
     o Listen( Socket sock, Integer port )
    Assigns a socket to listen for connection requests on a specified port.
     o Read( Socket sock )
    Reads the input available from a socket as a String.
     o ReadBytes( Socket sock )
    Reads the input available from a socket as a Bytes.
     o StreamBytesUntil( Socket sock, Dynamic token, [Integer maxlength], [Integer msDelay] )
    Reads a Bytes the input available from a stream Socket until the given token is encountered.
     o StreamUntil( Socket sock, [Dynamic token], [Integer maxlength], [Integer msDelay] )
    Reads a String from the input available from a stream Socket until the given token is encountered.
     o Write( Socket sock, Dynamic val )
    Writes a String or Bytes to a Socket.

    Class Attributes

     o ConnectRequest
     Integer ConnectRequest
    

    The callback constant indicating a connection has been made. For internal use only.

     o E_BufferTooSmall
     Error E_BufferTooSmall
    

    An Error terminating a read operation due to too small a read buffer.

     o E_EndOfFile
     Error E_EndOfFile
    

    An Error terminating a read operation due to end of file.

     o E_Error
     Error E_Error
    

    The generic Socket Error.

     o E_UserCancelled
     Error E_UserCancelled
    

    An Error terminating a read or write due to a user's request for cancellation.

     o ReadReady
     Integer ReadReady
    

    The callback constant indicating a connection has been accepted and is now ready for reading. For internal use only.

     o kSecurityNone
     Integer kSecurityNone
    

    The Security constant indicating no security.

     o kSecuritySSL2
     Integer kSecuritySSL2
    

    The Security constant indicating SSL2 security.

     o kSecuritySSL3
     Integer kSecuritySSL3
    

    The Security constant indicating SSL3 security.

    Instance Attributes

     o pBlocking
     Integer pBlocking
    

    Set to False if the Socket should block on input.

     o pPeerIPAddress
     String pPeerIPAddress
    

    The String IP address of an established connection, if connected, Undefined otherwise.

     o pPeerPort
     Integer pPeerPort
    

    The Integer port number of an established connection, if connected. Undefined otherwise. Note that Sockets set to listen on a given port with Socket.Listen() have this set to Undefined.

     o pReadTimeout
     Integer pReadTimeout
    

    The Integer number of milliseconds that a read on the socket will timeout if no data is available.

     o pSecurity
     Integer pSecurity
    

    The Security used by this socket, one of Socket.kSecurityNone, Socket.kSecuritySSL2, or Socket.kSecuritySSL3. This feature may or may not be supported.

     o pStreaming
     Boolean pStreaming
    

    True if the Socket behaves like a stream. Once set to true, it may not be reverted to False again.

    Class Methods

     o Accept
     Boolean Accept(
                 Socket accept,
                 Socket request )
    

    Accepts a connection request with a specified Socket. A request must be accepted before data can be read and written.

    Parameters:
    accept - A fresh, unconnected Socket which will accept request.
    request - The Socket to which connection request was made, which has been assigned to listen on a given port with Socket.Listen().
    Returns:
    True if the connection was successfully accepted, False otherwise.

    Behavior is undefined, and possibly catastrophic, if accept is an old, unclosed Socket, or request is not a Socket which which has been assigned to listen as a server socket with Socket.Listen().

     o Close
     Boolean Close(
                Socket sock )
    

    Closes the specified socket, after flushing it.

    Parameters:
    sock - The Socket to close.
    Returns:
    True if the socket was successfully closed, False otherwise.
     o CompareIpAddresses
     Integer CompareIpAddresses(
                 String addr1,
                 String addr2 )
    

    Compares two IPv4 or IPv6 addresses.

    Parameters:
    addr1 - an IP address to compare
    addr2 - the other IP address to compare
    Returns:
    Zero if the addresses are equal, non-zero otherwise.

    The addresses given must be the same format (IPv4 or IPv6). It is invalid to compare an IPv6 address to an IPv4 address.
    However, you can compare an IPv4-mapped IPv6 address ("::ffff:127.0.0.1") with an IPv4 ("127.0.0.1") address.

     o Connect
     Boolean Connect(
                 Socket sock,
                 String host,
                 Integer port )
    

    Attempts to connect a Socket to the specified host name and port number.

    Parameters:
    sock - The Socket to connect.
    host - The String name of the host.
    port - The port number to which the connection should be made, which should be a positive Integer less than or equal to 65535.
    Returns:
    True if the Connection was successful, false or Error otherwise.

    Here is a short example which uses Socket.Connect() to determine the IP address of the host "www.opentext.com":

    Socket	sock = Socket.Create()
    String	host = "www.opentext.com"
    Integer	port = 2244
    
    Socket.Connect( sock, host, 80 )
    Echo( "Host IP = ", sock.( Socket.pPeerIPAddress ) ) 
    Socket.Close( sock )

    The output of the example is:

    Host IP = 204.138.115.98

    It also demonstrates how to access the attributes of a Socket. For a more thorough Socket.Connect() example, see the class description above.

     o Create
     Socket Create(
               [Dynamic featurename],
               [Dynamic callbackobj] )
    

    Creates a new Socket. The optional arguments are for internal use only.

    Parameters:
    featurename - The name of a Script callback feature in callbackobj to invoke when a connection request is made or data is available for reading. For internal use only.
    callbackobj - An Object with a callback Script feature featurename. For internal use only.
    Returns:
    The new Socket.

    For internal use only: the Script should contain a void Function taking a Dynamic argument which will be a List. The first List element will be the message constant, either Socket.ConnectRequest or Socket.ReadReady. The second element will be the socket that caused the callback. Note that a Connection Request must be accepted with Socket.Accept() before data can be read or written. See the example in the class description section.

     o Flush
     Void Flush(
             Socket sock )
    

    Flushes the output buffer of the specified Socket.

    Parameters:
    sock - The Socket to flush.
    Returns:
    No useful value.
     o GetAddrByName
     String GetAddrByName(
                 String hostname )
    

    Returns a string of the IP address resolved for the given hostname.

    Parameters:
    host - The String name of the host.
    Returns:
    Resolved IP address. An empty String is returned if the address could not be resolved.
     o Listen
     Boolean Listen(
                 Socket sock,
                 Integer port )
    

    Assigns the socket to listen on the given port.

    Parameters:
    sock - The Socket to assign to listen
    port - The port number on which the Socket should listen, which should be a positive value less than or equal to 65535.
    Returns:
    True if the Socket has successfully been assigned to listen on the given port, False if not (the socket may have already been assigned to listen).
     o Read
     String Read(
               Socket sock )
    

    Reads available data from the specified Socket into a String until input is exhausted or the input buffer is full.

    Parameters:
    sock - The Socket to read from.
    Returns:
    The String read, which may be of zero length if no input was available for reading, otherwise Error if the Socket could not be read, possibly due to end of file.
     o ReadBytes
     Bytes ReadBytes(
                Socket sock )
    

    Reads available data from the specified Socket into a Bytes until input is exhausted or the input buffer is full.

    Parameters:
    sock - The Socket to read from.
    Returns:
    The Bytes read, which may be of zero length if no input was available for reading, otherwise Error if the Socket could not be read, possibly due to end of file.
     o StreamBytesUntil
     List StreamBytesUntil(
                   Socket sock,
                   Dynamic token,
                  [Integer maxlength],
                  [Integer msDelay] )
    

    Reads a Bytes from a Socket until either input matching token is read or maxlength number of bytes are read. Note that the Socket.pStreaming attribute must be set to true on the Socket to make it a stream Socket before this operation may be performed.

    Parameters:
    sock  -  The stream Socket from which input will be read until either token is encountered, or maxlength bytes have been read.
    token  -  The token Bytes to read until.
    maxlength  -  If specified, the maximum number of bytes read before returning if token is not encountered. The default is a reasonable buffer size (4096).
    msDelay  -  If specified, the millisecond delay between read tries, this will allow clients to wait for input without being as much of a CPU hog.
    Returns:
    The Bytes read, or Error.

    See Socket.Connect() for an example on how to set an attribute of a Socket.

     o StreamUntil
     List StreamUntil(
                Socket sock,
               [Dynamic token],
               [Integer maxlength],
               [Integer msDelay] )
    

    Reads a String from a Socket until either input matching token is read or maxlength number of bytes are read. Note that the Socket.pStreaming attribute must be set to true on the Socket to make it a stream Socket before this operation may be performed.

    Parameters:
    sock - The Socket from which a String will be read.
    token - If specified, the token String to read until. The default is the empty String, meaning all available input is read.
    maxlength - If specified, the maximum number of bytes read before returning if token is not encountered. The default is a reasonable buffer size (4096).
    msDelay  -  If specified, the millisecond delay between read tries, this will allow clients to wait for input without being as much of a CPU hog.
    Returns:
    The String read, or Error.

    See Socket.Connect() for an example on how to set an attribute of a Socket.

     o Write
     Boolean Write(
                Socket sock,
                Dynamic value )
    

    Writes a String or the contents of a Bytes to the given Socket.

    Parameters:
    sock - The Socket to which the data is written.
    value - A String or Bytes to write to the Socket.
    Returns:
    True if the value was successfully written to the Socket, False otherwise or Error.