Macaulay2 » Documentation
Packages » Macaulay2Doc » The Macaulay2 language » system facilities » 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

- getWWW -- get a web page

### Menu

#### Creating a socket

- `openListener` -- see openListener(String) -- open a port for listening
- `openIn` -- see openIn(String) -- open an input file
- openInOut -- open an input output file
- `openOut` -- see openOut(String) -- open an output file
- `openOutAppend` -- see openOutAppend(String) -- open an output file for appending

#### Manipulating a socket

- endl -- end an output line
- flush -- flush output to file
- close -- close a file
- closeIn -- close an input file
- closeOut -- close an output file

#### Interacting a socket

- get -- get the contents of a file
- getc -- get a byte
- read -- read from a file
- scanLines -- apply a function to each line of a file
- fileLength -- the length of a file
- height(File) -- get window height
- width(File) -- get window width
- `atEndOfFile` -- see atEndOfFile(File) -- test for end of file
- echoOn -- turn on echoing
- echoOff -- turn off echoing
- isOpen -- whether a file or database is open
- `isReady` -- see isReady(File) -- whether a file has data available for reading
- `isOutputFile` -- see isOutputFile(File) -- whether a file is open for output
- `isInputFile` -- see isInputFile(File) -- whether a file is open for input
- `isListener` -- see isListener(File) -- whether a file is open for listening
- openFiles -- list the open files
- connectionCount -- the number of connections

The source of this document is in /build/macaulay2-88fgJW/macaulay2-1.25.11+ds/M2/Macaulay2/packages/Macaulay2Doc/ov_files.m2:509:0.