Can I connect to a nodejs server with socket.io from a button press? I got my page for example file:///home...site/index.html and a server running on my local machine for example localhost:8080. Can i connect to the server from my file with when i call a function, using xmlhttprequest or other means? How? Got links/tutorials?
I have a very simple socket.io example on GitHub: socketio-example
Update the index.html page in this example to look like this:
<!doctype html>
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket;
function makeConnection() {
socket = io();
socket.on('welcome', function(data) {
addMessage(data.message);
// Respond with a message including this clients' id sent from the server
socket.emit('i am client', {data: 'foo!', id: data.id});
});
socket.on('polo', function(data) {
addMessage(data.message);
});
alert('connected.');
}
function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.appendChild(el);
}
function marco() {
socket.emit('marco');
}
</script>
</head>
<body>
<button onclick="makeConnection()">Connect</button>
<button onclick="marco()">Marco!</button>
<ul id='messages'></ul>
</body>
</html>
This will establish the socket.io connection when the user clicks Connect. Then you may click Marco! to send a message and receive the Polo! response.
Related
I see this example on a precedent question on this link how to display a realtime variable in nodejs in HTML and i dont't see in real time the value of json file on client
despite the answer is defined correctly.
Moreover in the bash i launch the command node --inspect socketProva.js (socketProva.js is the name of my server file) and i see in the page of inspect this message "WebSockets request was expected". The strange thing is that the server show correctly in real time the data of json file but the communication with client it does not seem to happen.
Thanks for the answers and excuse for my bad english.
socketProva.js and index.html
var io = require('socket.io')(8080); // The port should be different of your HTTP server.
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('prova.json', 'utf8'));
io.on('connection', function (socket) { // Notify for a new connection and pass the socket as parameter.
console.log('new connection');
var incremental = 0;
setInterval(function () {
console.log('emit new value', obj);
obj = JSON.parse(fs.readFileSync('prova.json', 'utf8'));
socket.emit('update-value', obj); // Emit on the opened socket.
incremental++;
}, 1000);
});
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="messages"></p>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<pre id="incremental"></pre>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var socket = io('http://localhost:8080'); // Connect the socket on the port defined before.
socket.on('update-value', function (value) { // When a 'update-value' event is received, execute the following code.
console.log('received new value', value);
$('#incremental').html(value);
});
</script>
</body>
</html>
JSON File: prova.json
{
"football":{
"id": 1,
"home": "Liverpool",
"away": "Chelsea",
"score": "1-0",
"last scorer":"Gerrard"
}
}
If the prova.json don't change during time, there is no need to read it using fs.readFileSync. You can require it.
var obj = require('prova.json');
The full example is shown below: (remember I changed the client socket.io.js version)
server:
var io = require('socket.io')();
var data = require('./data.json')
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
setInterval(function () {
data.value = Math.random();
socket.emit('update-value', data);
console.log('message sent to the clients');
}, 1000);
});
io.listen(8080);
client:
<!DOCTYPE html>
<html>
<head>
<!-- this changed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="incremental"></div>
<script>
var socket = io('http://localhost:8080');
socket.on('update-value', function (data) {
console.log('received new value', data);
var $div = $('<div>');
$div.text(data.value)
$('#incremental').append($div);
});
</script>
</body>
</html>
And data.json:
{
"value": 1
}
I'm trying to configure a WebSocket in Scala. I have a function that broadcasts a bunch of JSON to a WebSocket. It works when I configure it through http://www.websocket.org/echo.html (inputting my own ws://localhost:9000/web-socket), but I need it to display the information on a new webpage.
To that effect I made a new webpage called client which is defined in my controllers as
def client = Action {
val data = new RedshiftData() // get the data
Ok(views.html.client(data))
}
In my views I have client.scala.html defined as (adapted from websockets.org)
#import datadump.RedshiftData
#(data: RedshiftData)
<!DOCTYPE html>
<html>
<script>
var wsUri = "ws://localhost:9000/web-socket";
var ws = new WebSocket(wsUri);
#data.pushToWebSocket
ws.onmessage = function (evt) {
var msg = JSON.parse(evt.data);
console.log(msg);
};
</script>
<body>
</body>
</html>
But, it never receives my message that I'm sending. How do I get it to listen to the message that I send out in the controller?
Edit: Answered below
New to Node.js here, I really want to know why this script hangs forever when I'm attempting to connect to the created server.
I've had this happen often enough when I'm trying to create a server and I'm not sure why, as it seems to happen with very similar code:
Node script:
var http = require("http");
var file = require("fs");
var server = http.createServer(function(request, response)
{
file.readFile("chat.html", "UTF-8", function(error, content)
{
if(error) { console.error(error.stack); response.end(); }
response.writeHead(200, {"content-type" : "text/html"});
response.end(content);
});
}).listen(1994, function(){console.log("Listening");});
var websocket = require("socket.io").listen(server);
websocket.sockets.on("connection", function(socket)
{
socket.emit("message", {"message" : "Hello World"});
});
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Chat</title>
<meta charset="utf-8">
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = websocket.connect();
socket.on("message", function(message)
{
console.log(message);
});
</script>
</head>
<body>
<div>Socket file.</div>
</body>
</html>
If there is an error then it should end the response and if there isn't it should end the response, or does it have something to do with the web socket?
Try changing how you are invoking socket.io:
var websocket = require('socket.io')(server);
websocket.on('connection', doStuff);
This example follows directly from the docs on GitHub.
The problem was with websocket.connect(). Socket.io uses io as a global object in the front end, not websocket. So it should have been io.connect().
I want to send data via socket.io to my client via nodejs.
The data I am receiving are from pusher.
I am using an express backend and loading my server like that.
#!/usr/bin/env node
var debug = require('debug')('testApp');
var app = require('../app');
var Pusher = require('pusher-client');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});
/**
* return pusher data
*/
var API_KEY = 'cb65d0a7a72cd94adf1f';
var pusher = new Pusher(API_KEY, {
encrypted: true
});
/**
* Socket.io
*/
var io = require("socket.io").listen(server, {log: true});
io.sockets.on("connection", function (socket) {
// This will run when a client is connected
// This is a listener to the signal "something"
socket.on("data", function (data) {
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function (data) {
console.log(data);
});
});
// This is a signal emitter called "something else"
socket.emit("something else", {hello: "Hello, you are connected"});
});
On my client I am running the following script:
index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js" />
<script src='/javascripts/socket.js'></script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %> Juhu!</p>
</body>
</html>
My socket.js file:
var socket = io.connect(window.location.hostname);
socket.on('data', function(data) {
var total = data.total;
//print data to console
console.log(data);
});
My problem is that nothing gets shown in the console in my webbrowser, even though the data is coming in at my nodejs application.
Any recommendation what I am doing wrong?
I appreciate your replies!
I do believe the problem is when you use: socket.emit("something else", {hello: "Hello, you are connected"});
but have this in client-side: socket.on('data', function(data) {.
When you emit, you use the channel "something else", but on the client-side you are checking on the channel "data".
So on client-side you should be having socket.on('something else', function(data){.
Hope I helped. There isn't much info I could find on sockets.io, so I do not know if there is a preexisting channel called 'data'. Do enlighten me if so :)
I've been working with Socket.IO for a few days and it's been both extremely exciting and even more frustrating. The lack of current documentation/tutorials has made learning it very difficult. I finally managed to create a basic chat system, but there is one glaring question. How do I secure it?
What's stopping a malicious user from copying (or editing) my code and connecting to my server? I can grab the username from my PHP script and submit it to Socket.IO so I can recognize them as that user (and the PHP has security of course), but what's stopping someone from just submitting an unregistered username?
How can I make sure that the events submitted are authentic and haven't been tampered with?
My basic socket.io chat for references.
Server:
var io = require('socket.io').listen(8080);
var connectCounter = 0;
io.sockets.on('connection', function (socket) {
connectCounter++;
console.log('People online: ', connectCounter);
socket.on('set username', function(username) {
socket.set('username', username, function() {
console.log('Connect', username);
});
});
socket.on('emit_msg', function (msg) {
// Get the variable 'username'
socket.get('username', function (err, username) {
console.log('Chat message by', username);
io.sockets.volatile.emit( 'broadcast_msg' , username + ': ' + msg );
});
});
socket.on('disconnect', function() { connectCounter--; });
});
Client:
<?php session_start() ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>untitled</title>
</head>
<body>
<input id='message' type='text'>
<div id="content"></div>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
$.ajax({
type: 'GET',
url: 'https://mysite.com/execs/login.php?login_check=true',
dataType: 'json',
success: function(data) {
var username = data.username;
socket.emit('set username', username, function (data){
});
}
});
socket.on('broadcast_msg', function (data) {
console.log('Get broadcasted msg:', data);
var msg = '<li>' + data + '</li>';
$('#content').append(msg);
});
$('#message').keydown(function(e) {
if(e.keyCode == 13) {
e.stopPropagation();
var txt = $(this).val();
$(this).val('');
socket.emit('emit_msg', txt, function (data){
console.log('Emit Broadcast msg', data);
});
}
});
</script>
</body>
</html>
It all works dandy, except for having absolutely no security.
If you can install a key-value store like Redis on your node server, you can access it remotely from your php server using a Redis client like Predis. All you have to do is updating the remote session store on node server when a new login/logout happens in your php server.
Check this post for details: Authenticate user for socket.io/nodejs
The excellent passport framework for express uses secure cookies to validate identity. There is even a module to access it from socket.io.