This code to add a socket occurs 3 times - it should be commoned up into a function.