I'm trying to come to terms with how WebSockets work in Node.js but I'm having some trouble with sending a message.
I have my WebSocket server configured as follows (index.js)
var ws = require("ws");
var wsserver = new ws.Server ({
server: httpserver,
port: 3030
});
wsserver.on (
"connection", function connection(connection) {
console.log("connection");
}
);
wsserver.on (
"open", function open(open) {
console.log("open");
}
);
wsserver.on (
"message", function message(message) {
console.log("message");
}
);
This seems to be working ok because I can establish the connection using
var wscon = new WebSocket("ws://192.168.20.88:3030");
Which then gives me the connection output on the server. If I try to use send though nothing seems to happen and no error messages
wscon.onopen = function(open) {
wscon.send("test message");
}
I must be missing something but I don't know what
I might have an answer for this but I'm not entirely sure just yet, I'm going to put this here just in case.
I think the problem is that the message listener is added to the wrong object (the server object), I tried to add the message listener to the connection object passed to the server and it seems to be working but I'm not 100% sure why
wsserver.on (
"connection", function connection(connection) {
console.log("connection");
connection.on (
"message", function message(message) {
console.log("message : " + message);
}
);
}
);
Which dependency works for me?
I have been using socketIO for a while now and it works perfectly for Node.JS API's / servers. There are millions of tutorials online for this framework and I'll tell you one them.
How to install?
If you use NPM as your package manager in Node.JS just down it with the following command:
npm install --save socket.io
In case you're using yarn you can install socketIO as following:
yarn add socket.io
Setup the socket server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
// Used for serving the HTML page (if used)
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
// Listen for new connections
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Now in index.html I add the following snippet before the :
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
In your front-end you are able to fire of an event via the socket by calling the following function / code:
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
In our case we emitted an event called chat message. So in order to receive the value send over the socket connection we call the following code in our backend / api:
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
and that is basically how you use socket with the library SocketIO. Hope this helped fixing your issue!
Related
I'm trying to create a socket in a client.js file to communicate with my server. I followed the official documentation ( https://socket.io/docs/#Using-with-Express ) with no success. Basically when I initialize my socket like this:
var socket = io();
i expect a message from my server (e.g. 'A user has connected') but nothing appear, letting me suppose that the connection never happens.
This is a project made on Glitch. I tried to follow socket.io documentation, simple examples or other questions tips. I both tried the suggested script before instantiate the socket and the cdn one.
//server.js
//dependencies
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
//listening to the port
http.listen(process.env.PORT || 3000, () => {
console.log("Listening on port " + process.env.PORT);
});
io.on('connection', function(socket){
console.log('A user has connected.');
});
//chat.html
//this is called right before </body>
<script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js'></script>
<script src='/socket.io/socket.io.js'></script>
<script src='/public/client.js'></script>
//client.js
var socket = io();
client.js is loaded as expected (and the console throws no errors) but i can't see 'A user has connected' as i'd expect.
You can check full source code here https://glitch.com/edit/#!/farlokko-advanced-node
Thanks.
UPDATE:
The problem was a wrong initialization of the passport.socketio module, which interfered with sicket.io . The main problem probably was a wrong store(memoryStore instead of mongo-store) and a wrong key for the cookie (express.sid instead of connect.sid).
Finally socket initialization was ok and had to be io.connect("host here").
As specified on the doc, you have to configure the client to connect to your localhost, and then, on the connection, you'll have your message :
<script>
var socket = io.connect('http://localhost'); // <--- HERE MAN
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
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'm trying to use this simple tutorial:
http://socket.io/socket-io-with-apache-cordova/
My node.js is working fine and i'm emulating to iOS without problem, but the socket.io isn't working, here is my javascript(the same way as the tutorial above):
app.initialize();
document.addEventListener('deviceready', function() {
console.log(socket);
socket.on('connect', function() {
socket.on('text', function(text) {
alert(text);
});
});
});
and one more thing how can i get this console.log to debug?
here is how i'm getting socket.io(the same way as the tutorial above):
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
here is my server.js(the same way as the tutorial above):
var server = require('http').createServer();
var io = require('socket.io')(server);
io.sockets.on('connection', function (socket) {
console.log('socket connected');
socket.on('disconnect', function () {
console.log('socket disconnected');
});
socket.emit('text', 'wow. such event. very real time.');
});
server.listen(3000);
I think, that the problem and the tutorial didn't told is how i would connect my cordova app with port 3000
I made it, this tutorial is very good but it's not totally right.
You have to connect the socket to your server first (i'm using localhost and port 3000, but if you're using some server outside, i think you've to just put the ip and port):
var socket = io.connect('http://localhost:3000');
and after that, you call "socket.io", here is my complete code:
document.addEventListener('deviceready', function() {
var socket = io.connect('http://localhost:3000');
socket.on('connect', function() {
socket.on('text', function(text) {
alert(text);
});
});
});
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
var socketHost = "http://localhost:3000";
var socket = io.connect(socketHost);
It is simple chat app using node.js and socket.io. This app work fine in my local computer but do not work when I upload it to the server: Please look at my code on remote server and the problem.
Here is the code snippet of client:
<script type="application/javascript">
var socket = io.connect();
eventHandler(socket);
function eventHandler(socket) {
socket.on('connect', function(){
socket.emit('adduser', prompt("What's your name?"));
});
socket.on('error', function () {
console.log("Connection error"); //It works after a few second with error
});
}
$(document).ready(function(){
.....
});
</script>
It looks like on the remote server Socket.IO 0.9.16 is installed (which is not up-to-date). If you're writing code according to new documentation this might be a reason why it doesn't work as you expected.
Try to upgrade Socket.IO to 1.0
This change worked for me:
you wrote this method:
var socket = io.connect();
Thanks to another help page, I switched this method to this:
var socket = io.connect('http://localhost:8080');
You can replace "localhost" with whatever ip address you use to access your server.
Also, just in case - if you haven't, it would be useful to include a connection notification on your server in the app.js file. mine looks like the following:
var fs = require("fs")
, http = require("http")
, socketio = require("socket.io");
var server = http.createServer(function(req, res) {
res.writeHead(200, { "Content-type": "text/html"});
res.end(fs.readFileSync(__dirname + "/index.php"));
}).listen(8080, function() {
console.log("Listening at http://localhost:8080");
});
socketio.listen(server).on("connection", function(socket) {
console.log("CONNECTED");
socket.on("message", function(msg) {
console.log("Message received: ", msg);
socket.broadcast.emit("message", msg);
});
});
You can also see the help page I linked to in case they have something that more closely relates to your issue.
Your page seems to be working for me. Make sure your page is fully loaded before executing your script. This is done by using window.onload like this:
<script>
window.onload = function() {
//Your code here
}
</script>
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?