Two Simple Scripts Talking Over TCPAuthor: Cal Dixon This pair of scripts shows how to send messages between two REBOL scripts. When you try running these, be sure to start the server first. There are four major steps for the server and three for the client. On the server you start by creating a "listen" port with the REBOL OPEN function. In this example we are making a connection on port 9097. You specify that this is a listen port by omitting the machine name part of the URL you are opening. Next we get a connection from the "listen" port. Then we can send data with INSERT and receive data with COPY. The example is shown below with a description of each line (then as the full script at the end of this document.) This is the server, so start by creating a listen port for the other script to connect to:
Now, wait for a connection to come in on the listen port:
When the script awakes, get the first connection:
Create a new window to use to talk to the other script:
In this window, when you press enter you will send the text through the port and put the cursor back in the text entry field. Below it is where text is put when it is received from the client script. When the button is pressed, close the connection and the listen port before quitting. The loop below waits for data from the other script, but processes GUI events while we wait:
This code uses COPY to read from the connection and display it. If the other script closes the connection, COPY will return NONE so we use ANY to make sure FOREACH has a block to work with. On the client we start with opening a connection to the listen port we created in the server script. Note that here we specify that we are connecting to a machine called "localhost" - this is a special name that always refers to the computer you are using. Now we can again use INSERT and COPY to send and recieve data. First open a connection to the server script:
Now, create a new window:
When you enter text and press enter, the text is sent through the port and the cursor is put back in the text field. The reply from the server is displayed in the INFO text area. When the button is pressed, the connection is closed before quitting. Here is the loop that waits for data from the other script:
This loop works identically to that found in the server script. Note that the server and client scripts are nearly the same. You can make a single script that works for both. To start the server, just run the script. To start the client, provide a -c argument to the script.
To provide the -c as an argument to the script, run the script from a shell or shortcut such as:
Or run it from REBOL console with:
|