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

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.

Related

How can I connect WebSocket listening to one port to Net socket listening to another, using NodeJS?

This is the approach I tried but not working. I can forward the incoming messages from the WebSocket connection to the NetSocket, but only the first one received by NetSocket arrives to the client behind the WebSocket.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const NetSocket = require('net');
const net = new NetSocket.Socket();
// Web socket
wss.on('connection', function connection(ws) {
console.log((new Date()) + ' Remote connection accepted ' + ws.remoteAddress);
ws.on('message', function incoming(message) {
console.log('Received from remote: %s', message);
net.write(message)
});
ws.on('close', function(){
console.log((new Date()) + ' Remote connection closed');
});
});
// Net socket
net.connect(8745, '127.0.0.1', function() {
console.log((new Date()) + ' Local connection accepted');
});
net.on('data', function(data) {
console.log('Received from local: ' + data);
// Iterate the connected devices to send the broadcast
wss.clients.forEach(function each(c) {
if (c.readyState === WebSocket.OPEN) {
c.send(data);
}
});
});
net.on('close', function() {
console.log('Local connection closed');
});
After a new research I noticed that the problem was in my swift code.
private func setReceiveHandler() {
webSocketTask.receive { result in
defer { self.setReceiveHandler() } // I was missing this line
do {
let message = try result.get()
switch message {
case let .string(text):
print("Received text message: \(text)")
case let .data(data):
So, just adding defer { self.setReceiveHandler() } to my function, it started to work.
Note the defer statement at the start of the receive handler. It calls self.setReceiveHandler() to reset the receive handler on the socket connection to allow it to receive the next message. Currently, the receive handler you set on a socket connection is only called once, rather than every time a message is received. By using a defer statement, you make sure that self.setReceiveHandler is always called before exiting the scope of the receive handler, which makes sure that you always receive the next message from your socket connection.
I've got the information from:
https://www.donnywals.com/real-time-data-exchange-using-web-sockets-in-ios-13/

React Native Parse LiveQuery error on socket

I am having trouble connecting to the LiveQuery server that I setup on the server side of my React Native project. I followed the instructions on the site verbatim, but can only manage to get 'error on socket' when I connect with numerous attempts by the server to reconnect.
Here is my server setup:
liveQuery: {
classNames: ['BekonRequest'],
}
var port = 1337;
server.listen(port, function() {
console.log('parse-server running on port ' + port); });
var parseLiveQueryServer = ParseServer.createLiveQueryServer(server);
server.listen(port, function() {
console.log('parse-server running on port ' + port);
});
var parseLiveQueryServer = ParseServer.createLiveQueryServer(server);
And my client side code:
let requestQuery = new Parse.Query('BekonRequest');
requestQuery.equalTo("username", "broncos#nfl.com");
let subscription = requestQuery.subscribe();
subscription.on('create', (requests) => {
console.log(requests);
});
Can anyone see why I am not able to connect successfully?

Can't connect to Chrome app tcp server through from outside my local network

I didn't manage to access fron internet to a chrome app tcp server.
firewall and home network well configured, I tried and managed with a native c++ tcp server through the same port.
My manifest is like that:
"sockets": {
"tcpServer": {
"listen": "*"
}
}
and my tcpServer is launched like that:
// ...
chrome.sockets.tcpServer.create({name:"chrome-local-tcp-server", persistent:false}, function(createInfo) {
_this.info = createInfo;
// Listening TCP server
chrome.sockets.tcpServer.listen(createInfo.socketId, "127.0.0.1", 8000, null, function(result) {
// ...
});
}):
Only localhost client connection work
function WebSocketServer(port)
{
this.port = port;
this.ips = [];
this.ip_serverInfo = {};
this.webSockets = [];
this.socketId_webSocket = {};
var _this = this;
chrome.system.network.getNetworkInterfaces(function(interfaces) {
interfaces.forEach(openSocket);
});
function openSocket(interface) {
chrome.sockets.tcpServer.create({name:"chrome-local-tcp-server", persistent:false}, function(createInfo) {
_this.ips.push(interface.address);
_this.ip_serverInfo[interface.address] = createInfo;
chrome.sockets.tcpServer.listen(createInfo.socketId, interface.address, port, null, function(resultCode) {
if (resultCode < 0)
{
console.log("Error listening: "+chrome.runtime.lastError.message);
}
else
{
console.log("tcpServer listenning on "+interface.address+":"+port, createInfo);
}
});
});
}
// New connection
chrome.sockets.tcpServer.onAccept.addListener(function(info) {
debug && console.log("tcpSocket accepted", info);
var ws = new WebSocket(info);
_this.webSockets.push(ws);
_this.socketId_webSocket[info.clientSocketId] = ws;
ws.closeTcpSocket = function(clientInfo) {
// close TCP connection
chrome.sockets.tcp.disconnect(clientInfo.clientSocketId, function() {
chrome.sockets.tcp.close(clientInfo.clientSocketId, function() {
console.log("tcpSocket closed", clientInfo);
delete _this.socketId_webSocket[clientInfo.clientSocketId];
arrayRemoveValue(_this.webSockets, ws);
});
});
};
});
// Connection error
chrome.sockets.tcpServer.onAcceptError.addListener(function(info) {
console.error("tcpServer onAcceptError", info);
});
// on received data
chrome.sockets.tcp.onReceive.addListener(function(info) {
//console.log("onReceive", info);
var ws = _this.socketId_webSocket[info.socketId];
if (ws)
{
ws.tcpDataReceived(info.data);
}
});
// on received error
chrome.sockets.tcp.onReceiveError.addListener(function(info) {
if (info.resultCode !== -15)
{
console.error("tcp socket onReceiveError", info);
}
});
}
You must understand what the "address" parameter of opening a server socket does. Sockets only listen to connections on a particular interface, represented by the network address.
In your manifest, you allowed your app to bind the socket to any interface with "listen": "*".
However, inn this line:
chrome.sockets.tcpServer.listen(createInfo.socketId, "127.0.0.1", 8000, null, function(result) {
// ...
});
You explicitly bind your socket to the address 127.0.0.1, which is a local-only interface. No other machine can connect to your machine through this address.
If you look at various Chrome app samles like this one, they feature interface selection. From looking at Chrome source, e.g. here, it seems like API does not allow to bind to "any interface" like INADDR_ANY can.
So, you need to gather available interfaces with chrome.system.network.getNetworkInterfaces, and either let the user choose, try to guess the appropriate interface, or just create a socket per every interface.
Apparently this needs further explanation. An open socket that listens to connections is bound to a certain network interface. A computer can have several interfaces, and as a consequence several IP addresses.
127.0.0.1 is a special network interface that only works locally. You need to bind to your machine's address (say, 192.168.1.2) to receive external connections. You don't need to know the IP of the person connecting, and not even your "external IP" if you're behind a port-forwarding router - only the address of your network card.
You can get all addresses assigned to your machine by declaring "system.network" permission and calling chrome.system.network.getNetworkInterfaces():
chrome.system.network.getNetworkInterfaces(function(interfaces) {
interfaces.forEach(function(interface) {
console.log(interface);
});
});
This will list all network interfaces. You either need to select one (by presenting a choice to the user, or somehow selecting one yourself) or you can bind a socket per interface to listen on them all. Here's an example of how it can be done:
chrome.system.network.getNetworkInterfaces(function(interfaces) {
interfaces.forEach(openSocket);
});
function openSocket(interface) {
chrome.sockets.tcpServer.create(
{name:"chrome-local-tcp-server", persistent:false},
function(createInfo) {
_this.info = createInfo;
// Listening TCP server
chrome.sockets.tcpServer.listen(
createInfo.socketId,
interface.address, 8000, null,
function(result) {
// ...
}
);
});
}
Solution found. I had to open the port in my windows firewall. That's not done automatically for this Chrome feature !

Using WebSockets on Samsung Smart TV

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.

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