I would like to communicate 2 web pages page1.html and page2.html. I have thought that page1 is related to a app1.js node application and page2.html to a app2.js node application. The idea is to send data from the page1.html to app1.js using websockets and then the app1.js will send the data to the page2.html. My first idea is that app1.js sends data to app2.js and then app2.js to the page2.html. I know how to use web sockets to communicate (client-server) the page1.html with the app1.js but how to send data from app1.js to app2.js? In the app1.js I have
io = require('socket.io').listen(3000); //and
io.sockets.on('connection', function (socket) {
socket.on('GETDATAFROMPAGE1', function (data){
.....I Get data to be sent to app2?
});
}
Do I need to create a new io2 for other port? How can I do to send data to the app2.html?
I know how to do a client server communication but I don't know server-server communication and how to mix both
Summary: page1.html -> app1.js --> app2.js --> page2.html using websockets
Thanks for your answer
Seems like you can implement this in an easy way but you don't know because you said you want to send data from page1 to app1 and from app1 to app2 and from app2 to page2. So Basically if I got you correct, you want to send data from page1 to page2. You can create only one server in app.js and use socket.io to connect both pages to send data to each other.
Let's say you have page1.html:
socket.emit('GETDATAFROMPAGE1', data);
and page2.html:
socket.on('dataFromPage1', function(data){
//do something
});
and you have app.js:
io.sockets.on('connection', function (socket) {
socket.on('GETDATAFROMPAGE1', function (data){
socket.broadcast.emit('dataFromPage1', data)
});
}
The broadcast event only emits to other than the sender of the data. Now you can send data from page1.html to server and from server to page2.html
You have two options:
1) create HTTP routes which handle posting/getting data back end forth between both servers (I assume that it is trivial and you know how to configure route and get/post date between the servers)
2) you can use sockets on the server level as well. Take a look at node's net documentation http://nodejs.org/api/net.html
your code would look something like this:
//server
var net = require('net');
var server = net.createServer(function(c) { //'connection' listener
console.log('server connected');
c.on('end', function() {
console.log('server disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
console.log('server bound');
});
//client
var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' listener
console.log('client connected');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});
You can also use json-socket.
Related
I need send data from one page to another page using Socket.io in node. Both pages have different script. The pageA have the script fileA.js, and the pageB have the script fileB.js Here's my code:
fileA.js
$('canvas').on('mouseup', function() {
var dataCan = JSON.stringify(canvas);
socket.emit('upcanvas', dataCan);
});
and this the page that receives that data:
fileB.js
var socket = io.connect('http://localhost:3000');
socket.on('get-data', function(data){
console.log(data);
});
And Here's the server file that receive that data and send the events of socket:
server.js
//Sockets
io.sockets.on('connection', function(socket)
{
socket.on('upcanvas', function(data){
socket.emit('get-data', data);
});
});
But that don't work!, I tried separately fileA.js and fileB.js and the socket works perfectly, but when I try to combine the emit/on events between that two pages, don't occurs nothing. What's wrong in that code?
I've found the solution !, simply this:
//Sockets
io.sockets.on('connection', function(socket)
{
socket.on('upcanvas', function(data){
socket.broadcast.emit('get-data', data);
});
});
I want to use the tcp net module in node.js, my clients will be browser and also not browser ( device ).
when I tried to run in the browser the index.html, my browser keeps loading looks like it looping..I dont know what's wrong in my code.
I tried use telnet it works fine, the problem is on the browser i cannot load properly the index.html
//app.js
var net = require('net');
var io = require('socket.io')(net);
var clients = [];
var server = net.createServer(function (socket) {
console.log("New client connected");
clients.push(socket);
});
server.listen(1337, 'localhost', false, function () {
console.log('server bound');
});
io.on('connection',function(socket){
socket.emit('news', { hello: 'world' });
});
here is my client code.
http://pastie.org/10115599
Both the browser and socket.io require an http server, not just a TCP server. You can see the code examples in the socket.io documentation. The first server and client code example on that doc page shows you the basics you need.
In fact, the first step in socket.io connection is an http request that is then "upgraded" to the webSocket protocol. So, the server must be an http server. And socket.io hooks into an http server in order to receive incoming connections.
Here's a code example from the socket.io doc:
Server Code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
app.listen(80);
io.on('connection', function (socket) {
// incoming socket.io connection established
});
function handler (req, res) {
// process http requests for normal web page serving
}
Client Code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I am trying to connect to a socket.io-client using the following code:
Server:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
I don't get the Connected console log or Client Connected console log and I don't know why! The code sample is taken from another question posted: Link and I don't see any solution to the problem...
Use the same version of socket io client and server. It will work perfectly.
Also you need to add protocol with path.
change
var socket = io.connect('localhost:8080', {reconnect: true});
to
var socket = io.connect('http://localhost:8080', {reconnect: true});
Assuming you are using a socket.io version greater than 1.0, on the server, change this:
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
to this:
// Add a connect listener
io.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
See the socket.io documentation reference here.
You don't want to be listening for this event only on already connected sockets. You want to listen for this event on any socket, even a newly created one.
Also, be very careful when reading socket.io code in random places on the internet. Some things changed significantly from v0.9 to v1.0 (I don't know if this was one of those things or not). You should generally always start with the socket.io documentation site first since that will always represent the latest version. Then, if looking at other internet references, make sure you only use articles that are later than mid-2014. If you don't know the vintage of an article, it's best not to rely on it without corroboration from a more recent article.
you can use localhost. It works for me as well. You must use your ip address and port that works for you
I am new to Node.js and Socket.io. I am supposed to connect through a server using Android but I want to test first if I can connect to Node/Socket server using a browser like for example typing http:server:8000/?v=1&username=test&password=test. Is this possible?
I think the tutorial, on socket.io webpage (http://socket.io/), is a good start for you.
In a nutshell, you create a server that will listen for events like this piece of code:
// Load socket.io module and start listening on port 8000
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function (socket) {
// This is trigerred on a login event sent from the client
socket.on('login', function(data) {
// Do what you want with your data here
// Then emit a response
socket.emit('login-response', {data: 'ok'});
});
});
And on the client side you create this:
<!-- Load the socket.io library -->
<script src="/socket.io/socket.io.js"></script>
<script>
// Connect to your server
var socket = io.connect('http://localhost');
// Emit your login event
socket.emit('login', {username: 'test', password: 'test'});
// When you retrieve the login response
socket.on('login-response', function (data) {
console.log(data);
});
</script>
Here's my problem:
I have server A, running node.js and using socket.io for communicating with clients (web browsers). This all is running fine and dandy.
However, now that I have server B, which also needs to connect to server A through websockets, I have hit a wall. None of the node.js websocket clients I've found won't work with the socket.io on the server A.
So, this is the case I'm striving for:
.--------. .----------. .----------.
| CLIENT | <--> | SERVER A | <--> | SERVER B |
'--------' '----------' '----------'
Client-server A connection is done through socket.io
Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...
Even the example code in socket.io-client module doesn't work... :/
// Connect to server
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected.');
});
The code just passes without any errors and execution ends after few seconds.
Update: Code samples
Server (which works just fine) looks like this:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client looks like this
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
1, 2 and 3 prints out just fine, no errors, and few seconds later the process just exits
Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".
For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.
Required package is:
npm install socket.io
Node-App-1 server.js:
var io = require('socket.io').listen(3000);
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
socket.on('serverEvent', function (data) {
console.log('new message from client:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent to the clients');
}, 3000);
});
Node-App-2 client.js:
var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
reconnection: true
});
socket.on('connect', function () {
console.log('connected to localhost:3000');
socket.on('clientEvent', function (data) {
console.log('message from the server:', data);
socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
Turns out I was using old examples, for some reason, even though I triple checked them. Well, doh.
Also, it turned out that the socket.io-client is broken on latest Node (6.x.x). Managed to find an update from github for it, replaced the files and yay, everything's working!
Edit: Unfortunately I didn't save any links to working examples but after quickly skimming through the code it seems that the only changes were to the client code, which now looks like this:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
Here is a snippet of code I wrote, it's using socket.io 1.0.6 and socket.io-client 1.0.6. The case is the following:
Server A (Socket.io Client) <---> Server B (Socket.io Server)
Server B (Server):
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res)
{
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket)
{
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Server A (Client):
console.log('1');
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
If I'm using localhost:8080 only on the client server it doesn't connect.