Getting started with BlueSocket and SPM

I recently had a need for regular TCP sockets in Swift on macOS, and unfortunately my go-to iOS socket library, SwiftSocket, is iOS only. A quick peruse of showed a significant lack of other options.

I then found BlueSocket by IBM (?!), which appeared to do roughly what I was after. Unfortunately, BlueSocket doesn’t use Cocoapods but instead Apples own Swift Package Manager, which has a significant lack of documentation and like Swift itself, changes week-to-week.

Fundamentally this is very straight-forward, but worth documenting here because it doesn’t appear to be elsewhere. This was done on:

  • Xcode 8.1
  • Swift 3.0.1

First, we create a new Xcode project called BasicBlueSocket targeting a Command Line Tool for macOS in swift.


Now we need Swift Package Manager to come on board and get our dependency: BlueSocket.

Close Xcode and create the following file, named Package.swift in the root directory of our project folder:

import PackageDescription
let package = Package(
    name: "BasicBlueSocket",
    targets: [],
    dependencies: [
        .Package(url: "",
                 majorVersion: 0),

Now, open a Terminal and browse to the root of your project directory, where this file is located, and run: swift package generate-xcodeproj.

You should see SPM grab the required code from github and re-jiggle your folder structure:


If you now open BasicBlueSocket.xcodeproj, you’ll be able to go ahead and import Socket – the code library for easy sockets is now available.

We can test that we have BlueSocket up and running with the following code:

import Foundation
import Socket
print("I want a socket")
var socket: Socket
let webRequest = "GET / HTTP/1.1\r\nHOST:\r\n\r\n"
var responseData = ""
var data: Data = Data()
do {
    socket = try Socket.create()
    try socket.connect(to: "", port: 9999)
    try socket.write(from: webRequest)
    let result = try &data)
    let response = String(data: data, encoding: String.Encoding.utf8)
    print(response ?? "No Response Data")
} catch {

If you then run python -m SimpleHTTPServer 9999 in a Terminal and run the project, you should see a web request arrive in the python terminal, and the response show up in Xcode. Voila! easy sockets thanks to BlueSocket and SPM.