Navigation:  Programming Cookbook > Sockets Connectivity >

Streaming over a Socket Connection

Previous pageReturn to chapter overviewNext page

A generally more convenient method for transferring data across a Socket connection is to use streams. The Socket package includes two stream subclasses SocketReadStream and SocketWriteStream for this purpose. These classes also provide a buffering mechanism that, under most circumstances, dramatically increases performance.

Each Socket supports both a read stream and a write stream and these can be accessed using the #readStream and #writeStream methods respectively. Once you have an appropriate stream object you can use the standard Stream protocol for sending and receiving data. The only additional methods are #flush, for flushing out the buffers of a SocketWriteStream, and #hasInput, for checking the presence of data on a SocketReadStream without the need for blocking.


Let's perform our previous experiments again, but this time using the Socket streams. In the Client workspace:

socketB writeStream nextPut: 255.

socketB writeStream nextPutAll: #[1 2 3 4].

socketB writeStream nextPutAll: 'hello'.

socketB writeStream flush.


Note the need to finally flush the buffer of the SocketWriteStream to ensure all data is actually sent. Now, in the Server workspace, let's receive the data using the SocketReadStream associated with socketA. Display the results of evaluating the following:


socketA readStream hasInput.

socketA readStream next.

socketA readStream next: 4.

(socketA readStream next: 5) asString.

socketA readStream hasInput.


You'll probably find yourself using the stream interface for the majority of your work. As you can see from the above examples, it is useful for sending both binary and textual data, which makes it ideal for use when one end of the connection perhaps isn't even written in Smalltalk. You might find yourself wanting to write a connection between a Dolphin server and a Java client or, maybe, a C++ server and a Dolphin client. The stream interface will adequately support such scenarios.