Example

Creating a Server Port

Author: Paul Tretter
Return to REBOL Cookbook

Creating a server port is much different than a client port connection. The reason is because one server port must handle the data for many clients. The following shows how multiple clients can communicate with the REBOL server.

First off you create a listen port (server port)- such as:


    listen: open tcp://:12345

Now you have a listen port, but this port only listens for the connections so if you do a wait just on this port it will only respond to the connections and not the actual data sent from a remote connection. But we still have to wait on this port to monitor incoming connections:


     waitports: [listen]
     wait waitports

Now we need to perform some check to identify incoming port connections. This is done by checking to see if there is an active port connection with:


    first listen

This will return the active connection but not the data. This actually creates a new port object referencing this specific remote connection. We want to capture this remote connection for other communications so we would now have:


    active-port: first listen

Active-port will contain a new remote connection's details into a new port object. So we add more code and logic and to this point would be:


    listen: open tcp://:12345
    waitports: [listen]
    forever [
        data: wait waitports
        if same? data listen [
            active-port: first listen
        ]
    ]

We need to get the data that was sent but first we must wait on the new active-port so we append it to waitports.


    listen: open tcp://:12345     
    waitports: [listen]
    forever [
        data: wait waitports
        if same? data listen [
            active-port: first listen
            append waitports active-port
        ]
    ]

To wait for port data on this port we again have to perform some logic and capture the incoming data and in this case print it. We modify our 'if statement to an 'either statement.


    listen: open tcp://:12345
    waitports: [listen]
    forever [
        data: wait waitports
        either same? data listen [
            active-port: first listen
            append waitports active-port
        ][
            incoming-from-remote: first data
            print incoming-from-remote        
        ]     
    ]

You can test this by running the above code from one console and the following from another:


    from-remote: open tcp://localhost:12345
    insert from-remote "test"

Leave that console open and open yet another console and doing the same again but with "test2" as our string value.


    from-remote2: open tcp://localhost:12345
    insert from-remote2 "test2"

Now you have successfully made a server that can handle multiple clients.

Also notice that you can telnet to this port and send data also with:


    telnet localhost 12345

2006 REBOL Technologies REBOL.com REBOL.net