OScript API/Built-in Package Index

Class: Socket

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:

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

The callback constant indicating a connection has been made.

An Error caused by too small a buffer used during a read.

An Error caused due to end of file during a read.

A generic Socket Error.

Your networking software may have been incorrectly installed. Please check your installation notes.

An Error caused by the user canceling the socket read or write.

Security constant indicating no security.

Security constant indicating SSL2 security.

Security constant indicating SSL3 security.

Service id for a Livelink request.

Service id for a ping request.

Service id for a status request

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

Type ID for a Socket interface.

Instance Attributes

True if block on input.

The Socket connection timeout in milliseconds.

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

The Integer Port of the connection, if connected, Undefined otherwise.

The Socket read timeout in milliseconds.

The security layer used by the Socket.

True if the Socket should behave like a stream.

The Socket read timeout in milliseconds.

Class Methods

Accept( Socket accept, Socket request )

Accepts a connection request.

Close( Socket sock )

Closes and flushes the specified Socket.

CompareIpAddresses( String addr1, String addr2 )

Compares two IPv4 or IPv6 addresses.

Connect( Socket sock, String host, Integer port )

Connects a socket to a host and port.

Connects a socket to a host and port.

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

Creates a new Socket.

Flush( Socket sock )

Flushes the output buffer of a Socket.

GetAddrByName( String host )

Gets the address of the specfied host.

Listen( Socket sock, Integer port )

Assigns a socket to listen for connection requests on a specified port.

Read( Socket sock )

Reads the input available from a socket as a String.

ReadBytes( Socket sock )

Reads the input available from a socket as a Bytes.

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.

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.

Write( Socket sock, Dynamic value )

Writes a String or Bytes to a Socket.

Class Attributes

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

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

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

Error E_Error

The generic Socket Error.

Your networking software may have been incorrectly installed. Please check your installation notes.

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

Integer kSecurityNone

The Security constant indicating no security.

Integer kSecuritySSL2

The Security constant indicating SSL2 security.

Integer kSecuritySSL3

The Security constant indicating SSL3 security.

Integer kServiceIdLLi

Service ID for a Livelink request.

Service ID for a ping request.

Service ID for a status request.

Integer ReadReady

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

Integer SocketType

Type ID for a Socket interface.

Instance Attributes

Integer pBlocking

Set to False if the Socket should block on input.

The Integer number of milliseconds that a connection attempt will wait if the connection cannot be opened. If this is set to its default value of -1, a timeout specified by the operating system will be used.

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

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.

Integer pReadTimeout

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

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.

Boolean pStreaming

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

Integer pWriteTimeout

The Integer number of milliseconds that a write on the socket will wait if no data can be written.

Class Methods

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.

Example

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().

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.

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.

Example

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.

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.

Example

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

sock.pConnectTimeout = 15000 // 15 second timeout
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.

ConnectToLivelink

ConnectToLivelink()

Returns:

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.

Example

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.

Flush

Void Flush( Socket sock )

Flushes the output buffer of the specified Socket.

Parameters

sock

The Socket to flush.

Returns:

No useful value.

GetAddrByName

String GetAddrByName( String host )

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.

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).

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.

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.

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.

Example

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

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.

Example

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

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.

 Copyright © 2023 OpenText Corporation. All rights reserved.