Node.js: Socket.io doesn't work - node.js

I've wrote a simple node.js app by socket.io some weeks ago. My program is fine on my PC but when i tried to run it on my laptop. I faced a really weird error on my console.
note that I'm running node on 127.0.0.1:2324. I don't know what is that ip (0.0.9.20) on the chrome console.
Again, my code is correct cause it's working fine on my PC.
And I get this on my cmd:
my paint.html code is something like this:
<script src="http://127.0.0.1/node/paint/js/jquery.js"></script>
<script src="http://127.0.0.1/node/paint/js/cursor.js"></script>
<script src="http://127.0.0.1/node/paint/js/controllers.js"></script>
<script src="http://127.0.0.1/node/paint/js/core.js"></script>
<script src="http://127.0.0.1:2324/socket.io/socket.io.js"></script>
<link href="http://127.0.0.1/node/paint/css/style.css" rel="stylesheet" />
core.js:
// broadcat function
function broadcast(data)
{
var socketio = io.connect(serverPort);
socketio.emit("message_to_server", { pen : data});
}
// receive data from server
var socketio = io.connect(serverPort);
socketio.on("message_to_client", function(data)
{
var res_brush = data['pen'];
var brush_data_rec = res_brush['pen'].split('|');
draw(brush_data_rec[0],
brush_data_rec[1],
brush_data_rec[2],
brush_data_rec[3],
brush_data_rec[4],
brush_data_rec[5],
brush_data_rec[6]);
});
update:

You should explicitly specify the target hostname on the client to connect to to avoid confusing the client on which address to connect to. There's also a cleaner way to specify a target port.
var socket = io.connect('http://localhost/', {
'port': 8080,
'transports': ['websockets']
});

Related

Uncaught reference error require is not defined

I'm trying to use an html page in order to test the connection with my server.
I've got no problem with my server.js
var http = require('http');
var url = require("url");
// Chargement de socket.io
var io = require('socket.io').listen(server);
var server = http.createServer(function(req, res) {
var page = url.parse(req.url).pathname;
// Quand un client se connecte, on le note dans la console
});
io.sockets.on('connection', function (socket) {
console.log('Un client est connecté !');
});
server.listen(8080);
My client should is an html page here
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Communication test with socket.io !</h1>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://localhost:8000/server_node/node_modules/socket.io/lib/socket.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
</script>
</body>
</html>
Problem is, when I load the html client, I've got this error
socket.js:6 Uncaught ReferenceError: require is not defined
at socket.js:6
I'm not trying to implement a real client, I just want a simple page in order to do some connection test.
Thanks for your help
EDIT: Problem fixed, it was all because I wasn't loading the html file from the serverlike this fs.readFile('./ClientTest.html', 'utf-8', function(error, content) {
As this is just used to do some test, it's fine if it works this way; the client side will be with an other platform.
Sorry for that useless issue :(
You appear to be importing the server-side library on the client, you want to be importing the client-side one.
As per the docs, this is automatically served when socket.io runs on the server which you can import via
<script src="/socket.io/socket.io.js" />

Trying to create a socket between servers with SocketIO and PHPws

I'm having a bit of an issue with websockets. So, I have a Rpi that provides me some data through a socketIO client in a pretty simple way. The following code shows how do I get to get this data:
<!DOCTYPE html>
<html>
<header>
<title>SocketIO test</title>
<script src="http://192.168.5.5:8000/socket.io/socket.io.js"></script>
</header>
<body>
<script type="text/javascript">
var client = io.connect('http://192.168.5.5:8000');
client.on('connect', function() {
console.log('connected');
});
client.on('raw', function(data){
console.log(data);
});
client.on('state', function(data){
console.log(data);
});
</script>
</body>
However, what I need to implement is a little bit more complex. I need to use a Apache server to trait some of the data before it gets to the client side. The following image shows what I attempt to build:
To reach my goal I tried several WebSocket Servers and Client libraries for PHP until I found PHPws, which looks like the best solution for my scenario.
So, I read the examples, I test them and everything went well until I tried to connect to the Rpi with the following code:
require_once("../vendor/autoload.php");
$loop = \React\EventLoop\Factory::create();
$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);
$client = new \Devristo\Phpws\Client\WebSocket("ws://192.168.5.5:8000", $loop, $logger);
$client->on("connect", function() use ($logger, $client){
$logger->notice("Or we can use the connect event!");
$client->send("Hello world!");
});
$client->on("raw", function($message) use ($client, $logger){
$logger->notice("Got message: ".$message->getData());
$client->close();
});
$client->open()->then(function() use($logger, $client){
$logger->notice("We can use a promise to determine when the socket has been connected!");
});
$loop->run();
I've more or less taken this example from Devristo's github.
From the server side, the execution of the program is not throwing any error or message.
Is it possible to build what I want to build here with PHPws?
If so, am I connecting properly to de Rpi server with PHPws sample code shown?
It is possible :
[Node] Socket Server (This would be your RPi)
Simple socket.io server in node to check for a
(success) client connection event.
var io = require('socket.io')(1337);
io.on("connection",function(socket){console.log("[+] client",socket.id);})
[PHP] Socket Client
Using Elephant.IO we setup a client (Client Example for Socket.IO v2.0)
<?php
use ElephantIO\Client;
use ElephantIO\Engine\SocketIO\Version2X;
require __DIR__ . '/vendor/autoload.php';
$client = new Client(new Version2X('http://localhost:1337', [
'headers' => [
'X-My-Header: websocket rocks',
'Authorization: Bearer 12b3c4d5e6f7g8h9i'
]
]));
$client->initialize();
$client->emit('broadcast', ['foo' => 'bar']);
$client->close();
With this simple Client/Server example you will see the 'on connection' event in the node server when the browser opens the client.php

socket.io node.js server "debug: destroying non-socket.io upgrade" message

I have a node.js socket server using socket.io.
I'm building a firefox addon, where I load a pageworker. The html in the following page is as follows:
<html>
<head>
<script type="text/javascript">
//THIS DOESN'T WORK
var exampleSocket = new WebSocket("ws://someip:port");
exampleSocket.onopen = function (event) {
console.log("socket opened!");
};
//THIS WORKS
var exampleSocketa = new WebSocket("ws://echo.websocket.org");
exampleSocketa.onopen = function (event) {
console.log("socket to echo opened!");
};
</script>
</head>
<body>
</body>
</html>
I can open a websocket to echo.websocket.org, but not my own server. I get a "debug: destroying non-socket.io upgrade" message. I can switch it off with the option: { 'destroy upgrade': false }, but then I see no debug output from server, and no connection is made.
What am I doing wrong? How can I get a socket open to my socket.io server?
So after some more googling, it turns out that I need to require socket.io on the client side. Even though socket.io uses websockets, it prefers talking to itself.

now.js not ready

I have a bit of an issue. I'm trying to create a dynamic web app using node.js/express.js/now.js. I've done everything as shown in the small sample code at http://nowjs.com/download , with no success, the client-side now.js script hosted properly, but now.ready(..) never fires. The only differences are that I use express and my server which is used to initialze now.js is https.
Do you have any ideas which could cause it not to work?
server side:
var server = express.createServer(..);
..
server.listen(port, function() {..});
var nowjs = require('now');
var everyone = nowjs.initialize(server);
everyone.now.log = function(msg) { console.log(msg); }
client side:
<script type="text/javascript" src="/nowjs/now.js"></script>
<script type="text/javascript">
now.ready(function() { now.log('asd'); alert('asd'); });
</script>
Any help would be highly appreciated!
Best, Kornel
Well, found the answer.
Long answer: now.js has an issue when determining the communication port on which socket.io should communicate. This issue seems only to appear when using default https port (443).
I've found two solutions, the ugly one:
https://groups.google.com/forum/?fromgroups=#!topic/nowjs/8cO9D77tN2o
Basically you need to edit the source code of now.js at now/lib/fileServer.js and replace
var hostPort = options['port'] || host[1] || '80';
with
var hostPort = options['port'] || host[1] || ((request.headers.referer.split(':')[0] === 'https') ? '443' : '80');
The nicer one is to set port options to socket.io. Lucky us, this is supported by now.js:
var everyone = nowjs.initialize(server, {port: port, socketio: {transports: ['xhr-polling', 'jsonp-polling']}});
I hope that this will help others having the same issue and also hope that this behavior will be fixed later in now.js.
Best regards: Kornel
Running latest version of node and now on OSX, with Safari.
server.js
var html = require('fs').readFileSync(__dirname+'/index.html');
var httpServer = require('http').createServer(function(req, response) {
/* Serve your static files */
response.end(html);
})
httpServer.listen(8080);
var nowjs = require("now");
var everyone = nowjs.initialize(httpServer);
console.log('done');
everyone.now.logStuff = function(msg){
console.log(msg);
}
index.html
<script type="text/javascript" src="http://localhost:8080/nowjs/now.js"></script>
<script type="text/javascript">
now.ready(function(){
// "Hello World!" will print on server
now.logStuff("Hello World!");
});
</script>
done..
Start the server:
node server.js
Open your browser:
http://localhost:8080

now.js - Hello World example - "require not defined"

I'm having trouble getting the now.js chat client tutorial to work. (I've also followed this video almost exactly).
server.coffee:
fs = require 'fs'
http = require 'http'
now = require 'now'
server = http.createServer (req, res) ->
fs.readFile(
'index.html'
(err, data) ->
res.writeHead(
200
'Content-Type': 'text/html'
)
res.end(data)
)
server.listen 8080
everyone = now.initialize(server)
everyone.now.distributeMessage = (msg) ->
everyone.now.receiveMessage(#.now.name, msg)
index.html:
<html>
<head>
<title>nowjs title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/Flotype/now/master/lib/now.js"></script>
<script type="text/javascript">
$(document).ready(function() {
now.name = prompt("What's your name?", "");
now.receiveMessage = function(name, msg) {
return $("<div></div>").text("" + name + ": " + msg).appendTo("#msg");
};
return $("#send-button").click(function() {
now.distributeMessage($("#text-input").val());
return $("#text-input").val("");
});
});
</script>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text-input">
<input type="button" value="Send" id="send-button">
</body>
</html>
When I load up the server with node server.js,
I get an error that says "require not defined" on line 1 of now.js. Consequently, the client side code can't find the variable 'now'.
I understand that 'require' is a node function, but how do I get the client to understand that?
Any help will be appreciated.
The file you're including in your client source (../Flotype/now/master/lib/now.js) is the Node server side code that is included in your node process when calling now = require 'now'.
So changing your included client source file from .../Flotype/now/master/lib/now.js to /nowjs/now.js will fix your problem.
Where does this /nowjs/now.js file come from?
When using NowJS (and many other npm packages that do client/server communication) you extend the server object. This is done with the line everyone = now.initialize(server) (Code Here).
What the initialize function does is wrap your server with the fileServer (Code Here) class in NowJS. This adds a resource under the "folder" nowjs which serves the client now.js file.
I got this error when trying to run nodejs file with js command instead of node.
Eg: if the nodejs file name is test.js, I was doing
js test.js
instead of
node test.js
I hope this helps too for people searching for this error.

Resources