Checking if a socket is connected

Testing if a socket is still open isn’t as easy at it sounds. Anyone who has ever dealt with socket programming knows this is hassle. The general pattern is to poll on the socket to see if its still available, usually by sitting in an infinite loop. However, with f# this can be done more elegantly using async and some decoupled functions.

First lets write an async function that monitors a socket and returns true if its connected or false if its not. The polling interval is set to 10 microseconds. This is because if you set the interval to a negative integer (representing to wait indefinitely for a response), it won’t return until data is written to the socket. If, however, you have a very short poll time, you will be able to detect when the socket is closed without having to write data to it.

/// Async worker 
Read more

, ,

Reading socket commands

A few weeks ago I was working on a sample application that would simulate a complex state machine. The idea is that there is one control room, and many slave rooms, where each slave room has its own state. The control room can dispatch a state advance or state reverse to any room or collection of rooms, as well as query room states, and other room metadata.

But to do this I need a way to get commands from the control room in order to know what to do. In my application clients were connected via tcp sockets and I wanted commands to be newline seperated. This made it easy to test out via a local telnet (I didn’t need to design any binary protocol).

The socket

You can never assume you’ve read what you want off a socket, since you’re only ever guaranteed 1 or more bytes when a … Read more

, , ,

Dropped packets with promiscuous raw sockets and winsock

This article was originally published at

Lately in my spare time, I’ve been working on a tool that will decode serialized AMF over a tcp connection. AMF stands for action message format and is used to serialize binary data to actionscript applications. The idea is to have the tool work the way Charles does for JSON/AMF over http/https, except over TCP sockets. I really like the way Charles works, and it’d be nice to not have to go to Wireshark and try and piece through binary data when I’m debugging.

So how would I do this? TCP sockets are connection oriented, you connect to some host and port and you only recieve and send data to that port. That’s great and all, but you can’t always inject yourself as a proxy in a connection; it’d be nice to be able to just sit in the middle of a conversation … Read more

, ,