chickadee » websockets » receive-message

(receive-message #!optional (ws (current-websocket)))procedure

Read in a message from the client. Returns two values. The first is the message and the second is the message type, either 'text or 'binary. Regardless of the message type the message itself will always be a string. Takes an optional websocket object that is bound to (current-websocket) by default. It will always block until a message is received but if used within with-concurrent-websocket it will not block other messages from being received or processed and will return the first message that is finished being processed.

receive-message is "concurrent" aware so if it is used within with-websocket it will behave in a purely blocking fashion and when used within with-concurrent-websocket it will utilize the provided concurrency mechanism internally.

Note on performance: the websocket protocol requires all messages to be valid UTF8. The current validation process is extremely fast and generates very little garbage for UTF8 messages that only contain ASCII code points (chars less than 128), but is quite slow and uses a lot of memory when it contains higher plane code points. If you are processing a high volume of messages or exceptionally large messages it may be worthwhile to try to keep all or most messages ASCII only.

This method is thread safe.

A list of the possible message types (symbols):

  • 'text
  • 'binary
  • 'connection-close

If a message is of type binary then converting it to something possibly more "binary" like, such as a u8vector, could be done with the following. It will incur one copy of the data though.

(blob->u8vector/shared (string->blob msg))

You could also use a string port to read the data in different fashions.

(with-input-from-string msg
  (lambda ()
    (read-byte)
    (read-u8vector))) ; etc