How to start systemd services on incoming network traffic (XBMC example)


Systemd is a system and service manager which provides a neat and easy way to organize and start your services on Linux. Only recently I found out you can use .socket files to start services on incoming network traffic.

Usage with XBMC and XBMC Remote

For example you can use a .socket file to conveniently start xbmc when you connect via the XBMC Remote App. See the following .socket file:

#You might have to use the Service= and Accept=no options if the service name differs from the socket name

#This is the tcp port we listen to traffic to, set to the port you have set in xbmc->settings->network http control port


And the matching .service file:

#See comments for the xbmcnet.socket file above!
Description=Launch XBMC on main display - oneshot

User = xbmc
Group = xbmc
ExecStart = /usr/bin/xbmc-standalone -l /run/lirc/lircd
ExecStartPost = /usr/bin/bash -c "sleep 10 && systemctl start xbmcnet.socket"
#The sleep is needed because sometimes you are too slow with exiting the xbmc remote app and the traffic might start the service again immediately


Now you only need to start/enable the socket file and everything should be good to go!

systemctl enable xbmcnet.socket
systemctl start xbmcnet.socket