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>
Related
I'm using socket.io 1.7.3 version. Server code:
io.on('connection', function (socket) {
console.log(socket.id); // CdnNBVe9ktJmMcb1AAAA
socket.to(socket.id).emit('something');
socket.emit('something'); // if I do it without to, it works but to all clients
console.log(socket.rooms); // { CdnNBVe9ktJmMcb1AAAA 'CdnNBVe9ktJmMcb1AAAA' }
});
Client:
<script src="/socket.io/socket.io.js"></script>
var socket = io.connect(..);
socket.on('connect', function() {
console.log(socket.id); // CdnNBVe9ktJmMcb1AAAA
socket.on('something', function() {
alert('it works');
});
});
Why it doesn't work? I'm not getting any alert although all console.logs seems to be correct.
To send a message to the particular client, you must provide socket.id of that client to the server and at the server side socket.io takes care of delivering that message by using,
socket.broadcast.to('ID').emit( 'send msg', {somedata : somedata_server} );
In your code
socket.broadcast.to(socket.id).emit('something');
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 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.
I thought that socket.io would allow me to implement a websocket server. I have this very simple code:
// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');
// start at port 8888
var server = http.createServer(function(req, res) {
res.writeHead(200,{'Content-Type': 'text\html'});
res.end('<h1>Welcome to the Notification Server</h1>');
});
server.listen(8888);
// Create Socket.io obj/pass to server
var socket = io.listen(server);
socket.on('connection', function(client) {
console.log('Successful Websocket connection!');
client.on('message', function(event) {
console.log("Received message from client", event);
});
client.on('disconnect', function() {
console.log('Client has disconnected');
});
});
I've tried a few different test clients all of which generate this message on the server: debug - destroying non-socket.io upgrade
One such client attempt has some code like this:
<html>
<script type="text/javascript">
<!---
window.WebSocket = window.WebSocket || window.MozWebSocket;
var ws = new WebSocket("ws://dev.ourserver.com:8888");
ws.onopen = function() {
alert("Connected");
}
ws.onerror = function(error) {
alert("Error:"+error);
}
// -->
</script>
<body>
</body>
</html>
As soon as we load the page I get the debug message on the server.
I thought the point of this library was to support the websocket protocol and any client supporting websockets would be able to connect.
If I interpret the message literally it seems to indicate that server.io has detected that it is connecting to a "non socket.io" client. Does this mean that there is no way for me to connect to this server without using socket.io in the client?
I've set up a Ubuntu 10.04 server in my home network. I installed a lamp-server, NodeJs and Socket.io on it. It al seems to work fine but I can not make a connection from my client to the server. I think that I am missing the point of where to store the client files and/or how to the IP adress and port should be put in the code.
I'm using the example from David Walsh (http://davidwalsh.name/websocket). My ip-adress of the server is 192.168.1.113. On the client I store app.js in
/usr/local/bin
That is where node is installed as wel.
Server code
// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');
// Start the server at port 8000
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8000);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
When I start the server with Node and enter the adress in a browser (http://192.168.1.113:8000) I see 'Hello Socket Lover!' so I guess this works fine.
I store my client file (client.html) in
/var/www
That is where the home folder of my LAMP server is.
Client.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
var socket = new io.Socket('http://192.168.1.113',{
port: 8000
});
socket.connect();
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
}
</body>
</html>
Now when I open this file in a browser (http://192.168.1.113/client.html) nothing happens. I see no connection on my Ubuntu server or other logs and there are no messages in the browser.
Ehmm... what am I doing wrong? I've tried for hours, changing all kind of things but still no result.
With the help of pmavik (see comments) my question is answered.
What I didn't know was how to serve the client file properly (index.html). I copied an example from www.socket.io, added the right ip-adress and port and now a connection is made.
The server file (app.js) and the client file (index.html) should be in the directory where Node is installed. The Node-server sends the client file to the browser so there is no need to put the client file in the /var/www directory where the 'normal' files for websites are.
app.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8000);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html
<html>
<head></head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://192.168.1.113:8000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</body>
</html>