Macaulay2 » Documentation
Packages » Macaulay2Doc > The Macaulay2 language > using sockets
next | previous | forward | backward | up | index | toc

using sockets

It's easy to use sockets as though they were files. Simply replace the file name by a string of the form $host:service where host is the name of IP number of host to contact, and service is the port number or name to use. If service is omitted, then port 2500 is used. If host is omitted, then an incoming connection will be listened for.

The following code will illustrate two-way communication using sockets similar to the interaction used by web servers, and you may try it out on your machine, unless a firewall prevents it.

if (pid = fork()) == 0 then (
     try "$:7500" << "hi there" << close;
     exit 0;
sleep 2
get "$localhost:7500"
wait pid

The code uses fork to create a separate process that will listen for a connection on port 7500 and then send us a message. The sleep command pauses for a while to make sure the child process has had time to start listening. Then we use an ordinary input command, namely get, to obtain the message. Finally, we wait for the child process to finish, as we should.

See also