Networking With Alice Scripting

Networking capabilities open up a wide range of interesting applications that, if properly presented, broaden CS's appeal by incorporating more social and communal projects. For now, I will demonstrate the process of accessing a network resource from Alice; later articles will describe potential programming projects and support services.

Since I eventually want novice students to be able to use the networking functionality without being overwhelmed by the details, I am going to encapsulate the networking functions into an object that can be loaded and used in multiple worlds. My network object (which looks like a computer monitor) provides a method, getURLString, which takes a URL as a parameter and prints out the text of whatever document it finds there:

./images/network_setup.jpg

Network's Script

Objects in Alice can also have scripts associated with them. Since I want to package my network object for redistribution, the networking code is defined within the script for the network object:

from java.io import InputStreamReader
from java.io import BufferedReader

def getURLText(urlString):
        url = java.net.URL(urlString)
        reader = BufferedReader(InputStreamReader(url.openStream()))
        line = reader.readLine()
        data = ''
        while line != None:
                # convert new line characters to spaces
                data += line + ' '
                line = reader.readLine()

        network.serverData = data

I was not able to use the Python networking modules, but since Alice uses Jython as its backend, we have access to the full Java networking library. The function getURLText takes a URL string as a parameter, opens the URL, and reads it line by line converting new line characters to spaces (newlines don't display nicely in Alice "say" bubbles). Notice the use of the Java network and I/O libraries. The result is stored in the network object's serverData parameter.

Exposing the Script Via an Alice Method

The network object's getURLString method provides a friendly Alice interface to the networking script:

./images/network_method.jpg

The if block at the start of the method loads the network object's script if it has not already run. Unlike the world script, scripts associated with other Alice objects are not automatically executed when the world starts. Before we can use the networking function, the script must be executed, but it only needs to be run once, hence the if test.

The rest of the method is straightforward. The network object displays some information about what it is doing, retrieves the document specified by its parameter while flashing the screen, and concludes by printing out the text of the document it retrieved:

./images/network_alice.jpg