SocketReadMessage

SocketReadMessage[socket]

reads the next available message on the specified socket, returning it as a byte array.

Details and Options

  • The socket is specified as a SocketObject[].
  • For ZMQ sockets, SocketReadMessage returns the next discrete message sent to the socket. It returns all multi-part elements joined together into a single ByteArray.
  • For TCP sockets, SocketReadMessage will return a ByteArray of the data currently in the operating system buffer.

Examples

open allclose all

Basic Examples  (2)

Open a ZMQ socket and connect a client to it:

Writing a message from one side will send the message to the other side as a ByteArray:

Turn it into a string with ByteArrayToString:

Close the sockets:

For TCP sockets, the size of the message returned by SocketReadMessage is not deterministic and is controlled by the operating system:

Write out a large message from the server to the client:

Read messages from the socket until there is no more data available:

Confirm that the individual buffers add up to the entire message sent on the socket:

Close the sockets:

Scope  (1)

With ZMQ sockets, a single message is sent for every expression passed to WriteString:

Expressions can be written with Write and read back with Read, where each individual message sent is read back as a complete expression:

Expressions are written on the socket by default as a string in InputForm:

When writing expressions with Write, an additional newline message will appear in between expressions:

Applications  (1)

Define a flush function to remove all data sent on a socket:

There are now messages on the socket available to read:

Flush all of the messages to read new messages:

Now there is no data available; new data that is sent will show up first:

Close the sockets:

Neat Examples  (1)

Open up a TCP socket connection:

Connect a web browser to see the HTTP request written on the socket by the browser:

Nothing will appear in the browser window because we have not sent any HTTP response.

See the connected clients (there might be more than one, depending on your browser):

Read the requests from any ready sockets:

Close the connections to the clients:

Close the browser window that was opened.

Introduced in 2017
 (11.2)