Commits

Mathias Panzenböck committed 257ede4

only one web socket connection

  • Participants
  • Parent commits 349321d

Comments (0)

Files changed (1)

File javascripts/magnatune.js

 		return getBoolean('notifications.enabled');
 	},
 	PlayControl: {
-		_sockets: [],
+		_socket: null,
 		connect: function (host, port) {
 			var socket = new WebSocket("ws://localhost:8001/playctrl?"+$.param({
 				name: 'Greattune Player',
 			}));
 
 			socket.onopen = function () {
-				console.log("ws open");
-				Magnatune.PlayControl._sockets.push(socket);
+				try {
+					if (Magnatune.PlayControl._socket) {
+						Magnatune.PlayControl._socket.close();
+					}
+				}
+				finally {
+					Magnatune.PlayControl._socket = this;
+				}
 			};
 
 			socket.onmessage = function (event) {
-				console.log("message: "+event.data);
 				var message = JSON.parse(event.data);
 				switch (message.type) {
 					case "playPause":
 						Magnatune.Player.seekForward();
 						break;
 
+					default:
+						console.error("unknown message",message);
 				}
 			};
 
 			socket.onclose = function () {
-				console.log("ws close");
-				var i = Magnatune.PlayControl._sockets.indexOf(socket);
-				if (i >= 0) {
-					Magnatune.PlayControl._sockets.splice(i, 1);
+				if (Magnatune.PlayControl._socket === this) {
+					Magnatune.PlayControl._socket = null;
 				}
 			};
 
 			socket.onerror = function (event) {
-				console.log("ws error",event);
-				var i = Magnatune.PlayControl._sockets.indexOf(socket);
-				if (i >= 0) {
-					Magnatune.PlayControl._sockets.splice(i, 1);
+				console.log("web socket error",event);
+				if (Magnatune.PlayControl._socket === this) {
+					Magnatune.PlayControl._socket = null;
 				}
 			};
+
+			socket = null;
 		},
 		send: function (message) {
-			message = JSON.stringify(message);
-			for (var i = 0; i < Magnatune.PlayControl._sockets.length; ++ i) {
+			if (this._socket) {
 				try {
-					Magnatune.PlayControl._sockets[i].send(message);
+					this._socket.send(JSON.stringify(message));
 				}
 				catch (e) {
 					console.error(e);
 				}
 			}
+		},
+		disconnect: function () {
+			if (this._socket) {
+				this._socket.close();
+				this._socket = null;
+			}
 		}
 	},
 	Player: {