How to set up IPC in Swift using UNIX domain sockets

Viewed 312

I need to set up some relatively simple IPC for Mac and it needs to be done using UNIX domain sockets. I'm brand new to Swift so while I know this is possible I'm struggling even create my client and server. I have found a few useful resources for using UNIX domain sockets in other languages (Like this one: IPC using Unix Domain Sockets) but anything based in swift that I've found is more than I can follow at the moment in the brand new language. If someone could explain it like I'm 5 or at least point me in the right direction I'd appreciate it.

1 Answers

If you are more familiar with other languages - do it using other languages, and then incorporate into Swift.

Personally, I beleive that each language should be used to the things it doing best. Swift is not really doing best any of low-level stuff, but it could use libraries written in other languages, that are actually good in such things.

You can write the library on C or C++, working with sockets as you might find convenient, then make the Objective-C/C++ wrapper around it, then use the bridging-header to import Objective-C/C++ wrapper and use it from Swift code.

It may be a bit overhead in code size, but it would look nicer and be debuggable better, than having all this ugly Unsafe*** stuff in Swift.

For 5-y.o section: 0) Create 2 projects: Objective-C/C++ static library, Swift console app

  1. Write some nice API in .h file into lib, like "create, read, write" functions, implement them using resources you found in C or C++.
  2. Write some other .h file into lib with Objective-C/C++ API. You can really keep names and arguments, just change types to be NS* (std::string or char* -> NSString* and etc), and make this looks like class. Implement passing to C/C++ part in .m/.mm relevant file.
  3. Build the project 1, you should get an .a (static) library.
  4. Add a Bridging Header (it is a term, you could google it) to your Swift app, import there a Objective-C/C++ header. Add the .a library to Build Phases (Link Binary with Libraries). Use Objective-C/C++ class you created like it is Swift class for unix socket IPC.
Related