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');
Related
I know that messages can be sent outside the socket connection code block. How can I receive messages from the client the same way?
// Create socket.io server attached to current HTTP server
var io = require('socket.io')(server);
// When connection is made, set up some definitions for the server's connections
io.on('connection', (socket) => {
console.log('Local server connected...');
socket.on('disconnect', () => {
console.log('Local server disconnected...');
});
// I can receive messages here
socket.on('sendToRemote', function (data) {
console.log(data);
});
});
// Messages can be received outside the socket code using this syntax:
io.of('/').emit('runCamera', "Client connected...");
// I can't receive messages here...
// How can the server receive messages outside the socket code?
// I tried using the code below but it didn't work.
// Syntax compiles but doesn't work like the one above.
io.of('/').on('sendToRemote', function (data) {
console.log(data);
});
You need to have a socket to get messages from. You can emit to a room because it's tracking all the sockets connected to that room.
So to get messages only in a specific room:
io.of('/').on('connection', function (socket) {
socket.on("sendToRemote", function (data) {
console.log(data);
});
});
Client side code:-
<script src="/socket.io/socket.io.js"></script>
...snip...
var socket = io.connect( 'http://localhost:5000' );
socket.on('text_msg', function (data) {
socket.emit('message', {txt:"test"}); //this is not working
alert( data.msg );
});
Server Side Code looks like:-
const io = require('socket.io').listen(5000);
io.emit('text_msg', {msg: 'Welcome you are now connected.'}); //this is working good
// plain message - this never works
io.on('message', function(data){
console.log("message : " + data.txt); //No msg on console!
});
});
Please help me in sending message from client script to the server.
You are emitting the text_msg event right as you start your socket server, and not when a connection is made. You should listen for the connection event on the server, and then emit the welcome message to the connected socket.
The message that the client sends to the server also won't be seen because you are not listening for it. You need to listen on each individual socket.
Your server-sided code should look like this:
const io = require('socket.io').listen(5000);
io.on('connection', function (socket) {
socket.emit('text_msg', {
msg: 'Welcome you are now connected.'
});
socket.on('message', function(data) {
console.log('message : ' + data.txt);
});
});
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!
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>
I'm trying to write a basic chat application with Node.js (Express), and Socket.io. Everything 'seems' to be working, but my socket server seems to be only 'sending' the message back to the original sender. Here is my socket code:
var client = io.listen(app);
client.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
console.log(data);
socket.send(data);
});
});
And here is my client side code:
$(document).ready(function() {
var socket = new io.connect('http://localhost:3000');
socket.on('connect', function() {
socket.send('A client connected.');
});
socket.on('message', function(message) {
$('#messages').html('<p>' + message + '</p>' + $('#messages').html());
console.log(socket);
});
$('input').keydown(function(event) {
if(event.keyCode === 13) {
socket.send($('input').val());
$('input').val('');
}
});
});
Help is appreciated.
Use client.sockets.emit instead of socket.emit. It will emit to every connected client (broadcast), using the socket object only sends to the specific client.
Server side, I think you want:
socket.broadcast.emit(data);
instead of:
socket.send(data);
See "Broadcasting Messages" at the bottom of the "How to use" page. :)