Skip to content

Fake Telnet

Is some example code to demonstrate using NSStream. Download here.

It uses a category to append to NSTextView, which is a force of habit thing. An efficient append method which scrolls to visible should exist, that handles NSString and NSAttributedString (and quite possibly NSData with an encoding). While writing this category (or rather, rewriting it for the thousandth time, because it was quicker than finding an old copy – poor memory and poor organisation), I was browsing the documentation on the Text system, and thought I might try a variation – instead of using replaceCharactersAtRange:withString:, why not use insertText:?

Answer: because a non-editable NSTextView doesn’t have an NSTextStorage initially. This also means that early setString: will silently fail. I came across this a couple of months ago (or six) when running the Apple Cooca class on Tiger – one of the exercises fails, which used to work on earlier releases; the solution, from Mike Hoffhines, is to initialise an NSTextStorage.

The rest of the example code is in one class (MyController). It creates an NSHost given an input string, and uses NSStream getStreamsToHost: to start up. The rest is all handled by the handleEvent: delegate method. I have included a reasonable amount of logging so that it is possible to see what is happening in terms of events.

Most of the code is a copy from the Streams Cocoa Programming Topic; however, I added some checks to only write to a stream after receiving a NSStreamEventHasSpaceAvailable event, which the topic doesn’t give any help on. Also, it should be possible to check how much space is available, although I believe that isn’t relevant for these types of stream, so skipped that part.

For a server example (ie, listening on a port waiting for a connection), just use the link I gave yesterday to John R Chang’s NSStreamAdditions, which add a listen class method to NSStream.

Post a Comment

Your email is never published nor shared. Required fields are marked *