02
Sat, Nov
2 New Articles

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

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

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

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • 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

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • 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: