Using WebSockets on Samsung Smart TV - sockets

My requirement is to have a listening socket in my Samsung Smart TV app, in order to receive events from a device in the same local network.
I've been searching the web for methods to do that and I came across terms like Node.js, Socket.io, websocket. Even though i understand these terms in terms of web development (I think), I am unable to picture a method to open a listening socket in my Samsung Smart Tv App.
Just for the sake of playing around I wrote a TCP Server code on iOS using GCD Async Sockets and thought of connecting it to the smart tv and send a welcome message.
This is the code on my smart tv -
//var wsUri = "wss://echo.websocket.org/";
var wsUri = "ws://192.168.1.116:9898/";
//var output;
var webSocketObj={};
webSocketObj.init = function()
{
//output = document.getElementById("output");
this.testWebSocket();
};
webSocketObj.testWebSocket = function()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt); };
websocket.onclose = function(evt) { onClose(evt); };
websocket.onmessage = function(evt) { onMessage(evt); };
websocket.onerror = function(evt) { onError(evt); };
};
function onOpen(evt)
{
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
/* var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);*/
alert('SOCKET HELPER SAYS : '+message);
}
I have a button and I'm calling webSocketObj.init() on the button click.
Logs of my didReadData of the server :
Client says : GET / HTTP/1.1
Log from SmartTv :
[JS ALERT]: Scenewebsocket.handleKeyDown(29443)
[JS ERROR]:
File: file://
Line No: 0
Error Detail:
[JS ALERT]: SOCKET HELPER SAYS : DISCONNECTED
ALSO I tried echoing the message back to the Smart Tv from the server. And this time i got the logs
Client says : GET / HTTP/1.1
Client says : Upgrade: WebSocket
Client says : Connection: Upgrade
Client says : Host: 192.168.1.116:9898
Client says : Origin: file://
Client says : Sec-WebSocket-Key1: 1504l73 8Ew/J 4 ,L7W6
Client says : Sec-WebSocket-Key2: TK2 81d A64Bo7 118 0
I know i'm doing something horribly wrong...what is it? Pls help.

Have you tried socket.io server and client libraries?
We have socket.io server on node.js, and TV can connect to it using socket.io-client library. On 2012 TV it uses websocket. On 2011 TV it uses XHR fallback.

You can use socket.io library to make it easier for yourself to use WebSockets.
You would include a web browser version of socket.io in the samsung tv like this:
<script src="http://*some ip address*/socket.io/socket.io.js"></script>
Where some ip address is the ip address of a nodejs server that you control.
On your server you would need to install NodeJS with the socket.io server version.

Related

iPhone doesn't connect to the web socket but the simulator does

Physical devices cannot connect to my web socket. I tried it with 3 different phone and with different networks. It works fine with my simulators though. I am not getting an error message apart from the standard "Cannot connect to the server" from socket.io on the client.
I don't know if this is a valid indicator but I also tried using https://www.websocket.org/ with the following parameter:
wss://converzone.htl-perg.ac.at:5134
I am getting a "ERROR: undefined DISCONNECTED" there.
I am using an ubuntu server which runs Ubuntu 16.04. The web socket is from socket.io and I am coding with Swift on the client and with Node.js on the server. This whole thing is running on my school's server.
// Here is an array of all connections to the server
var connections = {};
io.sockets.on('connection', newConnection);
function newConnection(socket) {
console.log(socket.id + " connected.");
socket.on('add-user', function(user) {
connections[user.id] = {
"socket": socket.id
};
});
socket.on('chat-message', function(message) {
console.log(message);
if (connections[message.receiver]) {
console.log("Send to: " + connections[message.receiver].socket);
//io.sockets.connected[connections[message.receiver].socket].emit("chat-message", message);
io.to(connections[message.receiver].socket).emit('chat-message', message);
} else {
console.log("Send push notification")
sendPushNotificationToIOS(message.senderName, message, message.deviceToken, message.sound)
}
});
//Removing the socket on disconnect
socket.on('disconnect', function() {
console.log("The client disconnected");
console.log("The new list of clients is: " + connections)
for (var id in connections) {
if (connections[id].socket === socket.id) {
delete connections[id];
break;
}
}
})
}
Please understand that this problem seems very weird to me. I have changed the AppTransferProtocol in my plist and changed the port from 3000 to 5134. Nothing changed. Tell me what code would seem relevant apart from the (minimal) server code.

Where to register the Native Messaging Host in Chrome OS

In this documentation there's the location for Windows, Mac OS and Linux.
I assumed Chrome OS would work the same as "standard" linux, but i couldnt get my app working ...
com.my_app.host.json (located in /etc/opt/chrome/native-messaging-hosts/)
{
"name": "com.my_app.host",
"description": "My Host",
"path": "/home/user/bfd93db2180e0d7645b1f4cce2d2c7ed9e0d835c/Downloads/host.sh",
"type": "stdio",
"allowed_origins": [
"chrome-extension://APP_ID/"
]
}
main.js
var port = null;
var getKeys = function(obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}
return keys;
}
function appendMessage(text) {
document.getElementById('response').innerHTML += "<p>" + text + "</p>";
}
function updateUiState() {
if (port) {
document.getElementById('connect-button').style.display = 'none';
document.getElementById('input-text').style.display = 'block';
document.getElementById('send-message-button').style.display = 'block';
} else {
document.getElementById('connect-button').style.display = 'block';
document.getElementById('input-text').style.display = 'none';
document.getElementById('send-message-button').style.display = 'none';
}
}
function sendNativeMessage() {
message = {
"text": document.getElementById('input-text').value
};
port.postMessage(message);
appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>");
}
function onNativeMessage(message) {
appendMessage("Received message: <b>" + JSON.stringify(message) + "</b>");
}
function onDisconnected() {
appendMessage("Failed to connect: " + chrome.runtime.lastError.message);
port = null;
updateUiState();
}
function connect() {
var hostName = "com.my_app.host";
appendMessage("Connecting to native messaging host <b>" + hostName + "</b>")
port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
updateUiState();
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('connect-button').addEventListener(
'click', connect);
document.getElementById('send-message-button').addEventListener(
'click', sendNativeMessage);
updateUiState();
});
index.html
<html>
<head>
<script src='./main.js'></script>
</head>
<body>
<button id='connect-button'>Connect</button>
<input id='input-text' type='text' />
<button id='send-message-button'>Send</button>
<div id='response'></div>
</body>
</html>
It just says:
Connecting to native messaging host com.my_app.host
Failed to connect: Specified native messaging host not found.
Also i cant enable logging as explained in the documentation because on Chrome OS you cant just open Chrome via a command.
Would be great if someone could help me :)
Basically i just want to create a little GUI for launching Crouton commands.
Chrome OS does not support third-party native messaging hosts. As of writing, only two native messaging hosts are supported. One for testing, and one for Chrome Remote Desktop (source: native_message_host_chromeos.cc).
On Chrome OS, logs are available at /var/log/chrome/chrome and /var/log/ui/ui.LATEST. There are other ways to read/toggle the log (see
https://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/building-chromium-browser#TOC-Debugging and
https://github.com/ds-hwang/wiki/wiki/Build-Chromium-for-Chromium-OS-and-Deploy-to-real-device#log).
But the absence of built-in support for native messaging hosts does not mean that you cannot achieve what you want. Start a local HTTP server in Crouton, and communicate between the Chrome extension / app and the HTTP server via the standard Web APIs (XMLHttpRequest, fetch, WebSocket, ...). On the server (running in Crouton), you can do whatever you want (e.g. starting local scripts).
Make sure that the server implements proper authentication (to prevent unauthorized access by other web sites or extensions) (and preferably bind to a local address only to make the server inaccessible over network).

Calling of webservice in titanium mobile application code always return response with status code 0

I am new to titanium appcelerator family. Also I am not sure if somebody has posted the same problem before. I couldn't found it so posting it here.
I am developing one mobile application. And in my application I am trying to call one web service which is hosted on my local environment, but it is always returning response with status code 0 and error message "Can't reach host". So I thought that there should be some problem with my web service that I deployed on remote location. And hence I have tried to call some other web services like twitter, but it's same.. :( It is giving me an error while calling twitter web service also.
I also check for a cross domain policy issue. So I have also tried to set rule on server for web service, but it didn't work out. Following is code snippet and environment details that I am using.
Application type: Mobile
Titanium SDK: 2.1.4 GA
Device: Web Browser
Host Operating System: Windows 7
Titanium Studio: Titanium Studio, build: 2.1.2.201208301612
Files for sample web service which is I am calling is present on following locations:
http://db.tt/XoSCujux (api.php)
http://db.tt/bJG2A5XT (Rest.inc.php)
http://db.tt/Hxt6Oojx (.htaccess)
Code:
//declare the http client object
var xhr = Titanium.Network.createHTTPClient();
//this method will process the remote data
xhr.onload = function() {
//check to see if we are refreshing the data via our
//pull and release mechanism
//create a json object using the JSON.PARSE function
result = JSON.parse(this.responseText);
Ti.API.info(result);
console.log(result);
var msgTitle = "data:";
var msgText = result;
var alertBox = Ti.UI.createAlertDialog({
title: msgTitle,
message: msgText
});
alertBox.show();
};
//this method will fire if there's an error in accessing the remote data
xhr.onerror = function(e) {
//log the error to our titanium developer console
Ti.API.error(this.status + ' - ' + this.statusText);
console.log(this.status + ' - ' + this.statusText);
var msgTitle = "Error : " + this.status;
var msgText = "Error Text : " + this.statusText;
var alertBox = Ti.UI.createAlertDialog({
title: msgTitle,
message: msgText
});
alertBox.show();
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.' + e.error);
};
//open up the recipes xml feed
xhr.open("POST", "http://127.0.0.1/rest_example/api.php?rquest=locations");
//finally, execute the call to the remote feed
xhr.send();
Any help would be really appreciated.

socket.io: Failed to load resource

I'm trying to getting started with socket.io and node.js.
Following the first example on the socket.io's site I'm getting the following error in the browser's console:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3001/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined
This is my server.js
var app = require('express').createServer()
, io = require('socket.io').listen(app);
app.listen(3001);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
And this is my index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8" />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</body>
</html>
I've already installed socket.io..
The Issues
First of all you need to be looking at the server port that the server is bound on (app.listen(3001);) on the client side in order to reach the server at all.
As for socket.io, adding http://localhost:3001 before the rest of the source in the link tag solves this problem. This is apparently due to the way the network binds ports to localhost, however I will try to find some more information on the cause;
What to change:
The port binding for the server:
var socket = io.connect('http://localhost');
should be change to
var socket = io.connect('http://localhost:3001');
Making socket.io behave:
<script src="/socket.io/socket.io.js"></script>
should be change to
<script src="http://localhost:3001/socket.io/socket.io.js"></script>
If you are using express version 3.x there are Socket.IO compatibility issues that require a bit of fine tuning to migrate:
Socket.IO's .listen() method takes an http.Server instance as an argument.
As of 3.x, the return value of express() is not an http.Server instance. To get Socket.IO working with Express 3.x, make sure you manually create and pass your http.Server instance to Socket.IO's .listen() method.
Here is a quick example:
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
Firstly, the Socket.io "How To Use" documentation is vague (perhaps misleading); especially when documenting code for the Socket.io client.
Secondly the answers you've been given here on StackOverflow are too specific. You shouldn't have to manually hardcode the protocol, hostname, and port number for the Socket.io client; that's not a scalable solution. Javascript can handle this for you with the location object - window.location.origin.
Getting started with Socket.io
Installation
Socket.io requires the installation of a server and client.
To install the server
npm install socket.io
To use the client, add this script to your document (index.html)
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
Implementation with Express 3/4
Create the following files:
Server (app.js)
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Client (index.html)
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
// origin = http(s)://(hostname):(port)
// The Socket.io client needs an origin
// with an http(s) protocol for the initial handshake.
// Web sockets don't run over the http(s) protocol,
// so you don't need to provide URL pathnames.
var origin = window.location.origin;
var socket = io.connect(origin);
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
change;
<script src="/socket.io/socket.io.js"></script>
to;
<script src="https://cdn.socket.io/4.5.0/socket.io.min.js" integrity="sha384-7EyYLQZgWBi67fBtVxw60/OWl1kjsfrPFcaU0pp0nAh+i8FD068QogUvg85Ewy1k" crossorigin="anonymous"></script>
and drop between to head tags.
And Try it!
If you're trying to make this run on a different computer and you are getting this error, you may find this useful.
var host = window.location.hostname;
var socket = io.connect('http://' + host);
If you're using https, then obviously you need to change the protocol as well. In my case I needed to create a server that would run on several local computers, so putting here a fixed address would not work, as the socket would need to connect to a different address depending on what server you are loading the page from. Adding this here as it may help someone else too.
Try this
var app = express()
,http = require('http');
var server = http.createServer(app);
server.listen(3001);
io = require('socket.io').listen(server);
io.set('log level', 1);
Hope it helps
The following changes finally worked for me
const app = express(); const http = require('http'); const server = http.createServer(app); const io = require('socket.io')(server)
I know this is very very late, but I found a solution for those who might have previously set node.js up. My machine needed get hardware replaced, when it came back, I noticed quite a few settings were back to factory default. I was also getting the error discussed above.
Running
sudo apachectl start
from the terminal fixed up my issue.

Net Module Nodester not Listening to Port

I have a basic node.js app that is designed to open up a connection between two clients and echo the input of one to the other.
var net = require("net");
console.log("Relay Started");
var id = 0;
var Socket = [];
relay = net.createServer(function(socket) {
socket.on('connect', function() {
console.log('Connected');
if(socket.id==null) {
socket.id = id;
Socket[id]=socket;
id++;
}
});
socket.on('data', function(data) {
data = data.toString()
if (socket.id==0) {
Socket[1].write(data);
} else if (socket.id==1) {
Socket[0].write(data);
}
console.log(socket);
console.log(data.toString());
});
})
relay.listen(process.env['app_port']||8080);
It works fine when run locally, however when I put it onto a Nodester development server, I am unable to connect by using telnet zapcs.nodester.com 18007 (it is hosted under the name zapcs, and the given port is 18007). The Relay Started is logged, but nothing after that, and no connection. Any ideas on why this would be?
~
you can not telnet zapcs.nodester.com 18007, you only can connect to zapcs.nodester.com:80 by http or websock, nodester will route your request to your app actual port (18007) on the host.
And check this: http://www.slideshare.net/cmatthieu/nodester-architecture-overview-roadmap-9382423