next up previous contents index
Next: Stream-oriented, character-at-a-time interface. Up: Socket I/O Previous: General socket calls.   Contents   Index

Buffered, message-based communication.

These calls are similar to the recv and send calls in C, except that XSB wraps a higher-level message protocol around these low-level functions. More precisely, socket_send/3 prepends a 4-byte field to each message, which indicates the length of the message body. When socket_recv/3 reads a message, it first reads the 4-byte field to determine the length of the message and then reads the remainder of the message.

All this is transparent to the XSB user, but you should know these details if you want to use these details to communicate with external processes written in C and such. All this means that these external programs must implement the same protocol. The subtle point here is that different machines represent integers differently, so an integer must first be converted into the machine-independent network format using the functions htonl and ntohl provided by the socket library. For instance, to send a message to XSB, one must do something like this:


char *message, *msg_body;
unsigned int msg_body_len, network_encoded_len;

  msg_body_len = strlen(msg_body);
  network_encoded_len = (unsigned int) htonl((unsigned long int) msg_body_len);
  memcpy((void *) message, (void *) &network_encoded_len, 4);
  strcpy(message+4, msg_body);
To read a message sent by XSB, one can do as follows:

int actual_len;
char lenbuf[4], msg_buff;
unsigned int msglen, net_encoded_len;  

  actual_len = (long)recvfrom(sock_handle, lenbuf, 4, 0, NULL, 0);
  memcpy((void *) &net_encoded_len, (void *) lenbuf, 4);
  msglen = ntohl(net_encoded_len);

  msg_buff = calloc(msglen+1, sizeof(char))); // check if this suceeded!!!
  recvfrom(sock_handle, msg_buff, msglen, 0, NULL, 0);
If making the external processes follow the XSB protocol is not practical (because you did not write these programs), then you should use the character-at-a-time interface or, better, the buffered stream-based interface both of which are described in this section. At present, however, the buffered stream-based interface does not work on Windows.
socket_recv(+Sockfd,-Message, ?ErrorCode)

Receives a message from the connection identified by the socket descriptor Sockfd. Binds Message to the message. socket_recv/3 provides a message-oriented interface. It understands message boundaries set by socket_send/3.

socket_send(+Sockfd,+Message, ?ErrorCode)

Takes a message (which must be an atom) and sends it through the connection specified by Sockfd. socket_send/3 provides message-oriented communication. It prepends a 4-byte header to the message, which tells socket_recv/3 the length of the message body.


next up previous contents index
Next: Stream-oriented, character-at-a-time interface. Up: Socket I/O Previous: General socket calls.   Contents   Index
Baoqiu Cui
2000-04-23