Socketdemo.borg

Socketdemo.borg


{

`Open a second session(Bob).
`Open this file in it.
`Evaluate what's between the {} in both agents.
`Evaluate one by one the code after } in Alice.

`Extra: you can also close a socket if you are done with it
`Just use the function close(sock).

activesocket:0;

`Connecting a socket to a port and start listening
`max is number of allowed incomming connections
connectself(port, max)::
{
    `making a socket
    sock:socket();
    if(sock < 0, display("Error making socket" + eoln));
    `binding the socket to a port on the local computer
    err:socket_bind(sock, port);
      if(err = -1, display("Error binding socket to port " +text(port) + eoln));
      `listening at the port, max, is the number of incomming call's allowed
    err:=socket_listen(sock, max);
    if(err = -1, display("Error listening to socket port " + text(port) + eoln));
      activesocket:=sock
};

`accepting incomming conections
acceptself()::
{
    `accepting an incomming socket
    `used when we are listening at a port
    `return a new socket used to send and receive
    tmp:socket_accept(activesocket);
    activesocket:=tmp
};

`connecting a socket to one on another machines port
connectother(port)::
{
    sock:socket();
    `connecting the socket to another computer on a given port
    socket_connect(sock, "localhost:" + text(port));
    activesocket:=sock
};

sending(mes)::
{
    `sending the message (a string)
    socket_send(activesocket, mes)
};

receiving()::
{
    `receiving a string (empty if nothing was send)
     display(socket_receive(activesocket))
}
}


a:agent(router_placename()+"/Bob")

connectself(6699,10)

a->connectother(6699)

acceptself()


sending("how are you")

a->receiving()