tags:

views:

275

answers:

2

I have a remote Music Player Daemon(MPD) server running on a linux machine. I have a client listening to this stream on another linux machine.

When the MPD server is asked to pause or stop the stream, it disconnects all clients connected on the TCP port. Consequently, when the server starts streaming again, the clients have to be manually reconnected.

I want to write a program that will monitor the TCP port for a server accepting connections, and then automatically restart the clients. Can I do better than running connect() and sleep() in a loop? Are there any command-line utilities to do this?

I can run the client on the machine running the MPD server, if it will help. The following will tell me if a process is listening on a local port, but they do not block if a process isn't, so I still need to wrap them in a loop.

$ sudo fuser -n tcp 8000
8000/tcp: 9677

$ sudo netstat -nlp | grep 8000
tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 9677/mpd

I can try any solution that does not involve changing the behaviour of the MPD server.

+2  A: 

Here you go:

echo -n "" | nc -q 0 localhost 8000 && echo "made a connection" || echo "server was down"

echo -n "" puts an EOF immediately on stdin; nc -q 0 returns immediately after seeing that EOF on stdin. nc (netcat) tries to make a connection to localhost on port 8000. If it connects successfully, then it returns a successful error code and we echo "made a connection"; otherwise, if the connection was refused, we echo "server was down".

If you want to test it out, then in another terminal run

nc -lvvp 8000

which will start an instance of netcat listening on port 8000, with verbose output. In your other terminal, run the first command. The first time you run it, it will say made a connection. Then the server/listener will close, so the next time you run it, it will say server was down.

Mark Rushakoff
Isn't this similar to using fuser or netstat, except this can be run from another machine?
nagul
Yes, it absolutely can be run from another machine. Just put the remote hostname in place of localhost, of course. It's not precisely the same as netstat since the server could be set up on localhost only and therefore reject remote connections, for instance. But for your needs it's probably close enough.
Mark Rushakoff
+3  A: 

There is always the possibility of writing a relay server that proxies for MPD.

It sits there listening on a different port for your clients and makes connections to MPD in their stead. When MPD disconnects, the relay just attempts to reconnect every few seconds without disconnecting its clients.

quamrana