iSockets: The Cool, New, Free Way to Do Web Services

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

It's been awhile since I've built a free tool for the iSeries and AS/400 market.

First, I wrote something called DSPDBF (circa 1984) that allowed you to display and update any database file (physical or logical) in character mode or hex mode. Then, I did Q38TEXT (which I hear some people continue to use to this day); it was the first non-IBM word processor for this architecture. In fact, Q38TEXT may have been available before IBM's System/38 text processor. I don't remember. Then, there was Q38 UTILITIES, which became COZZI UTILITIES, a set of programs that eventually contributed to encouraging IBM to produce QUSRTOOLS.

On the iSeries, I created an early CGI library called CGI TOOLS that allowed you to more easily use the IBM-provided CGI APIs. Then, I built RPG xTools, a set of nearly 200 subprocedures that make doing complex API calls or day-to-day RPG IV tasks easier.

Enter iSockets

iSockets is a service program that contains about a dozen subprocedures that allow RPG IV programmers to easily communicate with Web services. For example, suppose you need to send a request to UPS to track a package. With iSockets, you simply open the UPS URL, send it your request, and receive the response back into your RPG IV program.

I would show you an example, but since the UPS license agreement seems to be over 10,000 words in length, I have no idea if I'm legally allowed to show it to you. (Do they really believe anyone has ever read that agreement?)

iSockets wraps traditional sockets programming into easy-to-use functions. While sockets programming may be commonplace to non-iSeries developers, it is not very common in our RPG world. iSockets makes using sockets simple. If you can call a subprocedure, you can open a socket to a Web services Web site.

A simple way to illustrate how iSockets helps is the GETURI example program. GETURI is an industry-wide routine that is used to open a Web page and read its contents (HTML tags and data) into a variable in your program.

Illustrated in Figure 1 is the GETURL program source code. I chose GETURL instead of GETURI because I discovered in the CGI Web programming classes I teach that most people think GETURI is simply a misspelling of GETURL.

     H OPTION(*NODEBUGIO:*SRCSTMT)  BNDDIR('ISOCKETS')
      /IF DEFINED(*CRTBNDRPG)
     DFTACTGRP(*NO)
      /ELSE
     NOMAIN
      /ENDIF

      /COPY ISOCKETS/QCPYSRC,iSockets

      /IF NOT DEFINED(*CRTBNDRPG)
     D GetURL          PR            10I 0
     D  URL                         128A   Const                                
     D  szRtnHTML                 65535A   OPTIONS(*VARSIZE)                    
     D  nRtnLen                      10I 0 Const                                


     P GetURL          B                   Export 
     D GetURL          PI            10I 0
     D  URL                         128A   Const                                
     D  szRtnHTML                 65535A   OPTIONS(*VARSIZE)                    
     D  nRtnLen                      10I 0 Const                                
      /ELSE
     D URL             S            128A
      /ENDIF

     D szURL           S            128A   Varying
     D hURL            S             10I 0
     D nBytes          S             10I 0
     D szHtml          S          65535A
     D pHtml           S               *   Inz(%addr(szHtml))
     D nPage           S             10I 0
     D nPageB          S             10I 0
     D nPageF          S             10I 0
     D szDomain        S                   Like(szURL)
     D szPage          S                   Like(szURL)
     D szParms         S                   Like(szURL)

      /IF DEFINED(*CRTBNDRPG)
     C     *ENTRY        PLIST
     C                   PARM                    URL

     C                   eval      *INLR = *ON    
      /ENDIF

     C                   if        %Parms >= 1
     C                   eval      szUrl = %trimR(URL)
     C                   endif
     C                   if        szURL = ''
     C                   return
     C                   endif

     C                   eval      nPageF = %scan('':szURL)
     C                   eval      nPageB = %scan('/':szURL)
     C                   if        nPageB = 0 and nPageF = 0
     C                   eval      nPage = 0
     C                   else
     C                   if        nPageB > nPageF
     C                   eval      nPage = nPageB
     C                   else
     C                   eval      nPage = nPageF
     C                   endif
     C                   endif
      ** Split the page being requested apart from the domain name.
     C                   if        nPage > 0
     C                   eval      szDomain = %subst(szURL:1:nPage-1)
     C                   eval      szPage   = %Subst(szURL:nPage)
     C                   endif

     C                   eval      hUrl = OpenURL(szDomain)
     C                   eval      nBytes=SendURLText(hUrl:'GET http://'+
     C                                    szDomain+ szPage + ' HTTP/1.0 ')
     C                   eval      nBytes =
     C                                RecvUrlData(hUrl:pHtml:%size(szHtml))
     C
     C                   callp     CloseURL(hUrl)

      /IF NOT DEFINED(*CRTBNDRPG)
     C                   if        nBytes <= nRtnLen
     C                   eval      szRtnHtml = %subst(szHtml:nBytes)
     C                   else
     C                   eval      szRtnHtml = %subst(szHtml:nRtnLen)
     C                   endif
     C                   return    nBytes
      /else
     C                   return
      /endif

Figure 1: Here's the source for the GetURL program.

The GETURL program is sort of polymorphic. I use preprocessor directives to condition the source code so that you can use it as either a standalone program or as a procedure within a module. It is controlled based on the compiler command being used to compile it. If you use CRTBNDRPG (PDM option 14), a standalone program is produced; if you use CRTRPGMOD (PDM option 15), a module is created, and the pieces unique to *PGM objects are discarded. I tested the program version of GETURL only in debug mode, but you could certainly add the ability to write the returned HTML (stored in szHTML) to a source or IFS file. That should be simple enough.

iSocket Interfaces

Today, we'll cover five of the iSocket subprocedures. The GETURL example uses four of them:

  • OpenURL opens a URL.
  • SendURLText writes character text strings to the open URL.
  • RecvURLData receives the response back from the Web services.
  • CloseURL closes the open URL.

OpenURL (Open a URL)

hURL = OpenURL( domain or IP address [ :nPort ]  )

The OpenURL subprocedure opens a socket to a domain name or IP address. The optional second parameter indicates the port number to use for communications. Normally, port 80 is used, so it's the default. If unspecified, the OpenURL subprocedure asks your system for the port number through which HTTP is running.

SendURLData (Send URL Data)

bytes-sent = SendURLData( hURL  : address-of-variable  : length-of-data-to-send )

The SendURLData procedure sends data to the open URL. The data to be sent is specified on the second parameter, and the length of the data to be sent is specified on the third parameter. The second parameter is a pointer to the data to be sent, not a variable. This means %add() is used to specify the second parameter. Here's an example.

This is correct:

SendUrlData(hUrl : %addr(myData ): %len(myData))

This is not correct:

SendUrlData(hUrl : myData : %len(myData))  

SendURLData returns the number of bytes written to the open URL. Check this value for zero or less than zero to ensure that your data is sent correctly.

SendURLText (Send URL Text)

bytes-sent = SendURLTexta( hURL  : text-variable or 'quoted-literal' )

This simplified version of the SendURLData iSockets procedure allows you to easily pass a text string to the open URL. Whatever you specify is passed.

RecvURLData (Receive Reply URL Data)

bytes-returned = RecvURLData( hURL  : address-of-variable  : max-length-to-return )

The RecvURLData procedure waits for the Web service to reply to your request. The response is copied into the second parameter (again the address of a variable), and the number of bytes returned is returned by RecvURLData. Here's an example:

nBytesRecv = RecvUrlData(hUrl : %addr(myData ): %len(myData))

CloseURL (Close an Open URL)

CloseURL(  hURL )

The CloseURL subprocedure closes an open socket to a domain name or IP address. Pass the handle to the URL (hURL) that you received when issuing the OpenURL procedure.

But Wait; There's More!

That's all I have time for this week. Next time, I'll cover the rest of the iSockets interfaces, including these:

  • GetURLData—Retrieve (e.g., steal) a Web page's content from within RPG IV
  • EncodeURI—Escape (encode) a URL component before sending it to a Web services routine
  • UnEncodeURI—Unescape a received URL component
  • UnEscapeURI—Unescape a received URL component
  • OpenCvtCCSID—Open conversion using From/To CCSID
  • CvtCCSID—Convert from one CCSID to another (e.g., ASCII to EBCDIC)
  • CloseCvtCCSID —Close and open conversion
  • Joblog—Write a text message to the joblog

Remember, iSockets is completely free and is available only at www.rpgiv.com/isockets or www.iSockets.net.

Bob Cozzi is a programmer/consultant, writer/author, and software developer of the RPG xTools, a popular add-on subprocedure library for RPG IV. His book The Modern RPG Language has been the most widely used RPG programming book for nearly two decades. He, along with others, speaks at and runs the highly-popular RPG World conference for RPG programmers.

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  •  

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: