I have a issue with socket.io with rooms.
See the server code:
This code below is working properly.
io.on('connection', function(socket){
socket.join("myroom");
socket.on('chat message', function(data){
io.in("myroom").emit('chat message', data);
});
});
But I want the user to enter the room after an event.
Like the code below.
io.on('connection', function(socket){
socket.on('chat message', function(data){
io.in("myroom").emit('chat message', data);
});
socket.on('join', function(name, device, room){
socket.join("myroom");
});
});
It's almost the same code , but does not work. What am I doing wrong?
The event is being called correctly.
Edit. Added the front-end code:
var socket = io.connect('http://localhost:5000');
$('#msg_form').submit(function(){
socket.emit('chat message', $("#m").val(), "myroom");
$('#m').val('');
return false;
});
$("#user").submit(function() {
var name = $("#name").val();
var room = $("#room").val();
var device = navigator.userAgent;
if (name === "" || name.length < 2) {
$("#errors").empty();
$("#errors").append("Please enter a name");
$("#errors").show();
} else {
socket.emit("join", name, device, room);
$("#messages").focus();
}
});
Thank you.
I made this small demo to explain, I simulate the client-side event by setTimeout functions:
Server side:
var http = require('http');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(9999);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.on('message', function(data){
io.in("myroom").emit('message', data);
});
socket.on('join', function(name, device, room){
console.log("new client has joining a room");
socket.join("myroom");
});
});
Client Side:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:9999');
setTimeout(function () { console.log("msg emmited to server");
socket.emit('join');
},
10000);
setTimeout(function () {
console.log("msg emmited to server");
socket.emit("message","message from client");
},
20000);
socket.on("message",function(data){
console.log("message received from server ="+data);
}
);
</script>
In your $("#user").submit(...) handler, you do not prevent the default action of the form so it is likely that the page is reloaded right after you hit the submit button. And, this will reset your connection right after you hit join, giving you a newly initialize connection that is not joined into the room.
You can either add return false; to that handler or add the e argument to the handler and call e.preventDefault() to prevent the page from reloading when you hit submit.
$("#user").submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var room = $("#room").val();
var device = navigator.userAgent;
if (name === "" || name.length < 2) {
$("#errors").empty();
$("#errors").append("Please enter a name");
$("#errors").show();
} else {
socket.emit("join", name);
$("#messages").focus();
}
});
Related
Client Side script
var socket = io.connect();
var room = "abc123";
socket.on('connect', function() {
socket.emit('room', room);
});
socket.on('message', function(data) {
console.log('Incoming message:', data);
});
Server side script
io = socketio.listen(server);
io.sockets.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
});
});
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party
people?');
I am trying to send message to abc123 but io.sockets is not working.
When no room is specified client receive the message but when specify a room I am unable to receive message on client.
server.js
var socket = require('socket.io');
var mysql = require('mysql');
const path = require('path');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = PORT;
io.on('connection', (socket) => {
console.log('new connection made');
socket.on('subscribe', function (room) {
socket.room = room;
socket.join(socket.room, function () {
console.log('joined:' + room); // outputs joined: 1
socket.on('send-message', (data) => {
io.to(data.room).emit('message-received', data.message);
console.log("sent to room:" + data.room); // outputs sent to room: 1
});
});
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
client.js
this.socket = io.connect('ws://IP:PORT');
this.socket.on('connect', () => {
console.log("connection made"); // it output connection made in console
this.socket.emit('subscribe', 1);
});
this.socket.on('message-received', (message: any) => {
console.log(message);
});
on server.js I have tried several options below but still unable to emit 'message-received' on client side:
// io.emit('message-received', data);
// io.to(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
// io.sockets.in(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
//io.broadcast.to(data.room).emit('message-received', data.message);
using latest socket.io library with angular 4
based on what i see on your clientside and serverSide code, I believe the problem is in the clientSide code...
On your server, inside the 'subscribe' event the server is also listening for 'send-message' event, which you're never emiting from the client side!!
Therefore, if you emit 'send-message' event with data(this should include message) as parameter, only then the server would emit 'message-received' event to the client..
HOPE THIS HELPS!
I want to send message to users if some new person is joining or user is quiting the chat.
i don't really know where to start to get this function work.
On disconnect message 'This users is gone' to all On Connect "user is connected to the chatbox"
app.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
nicknames = [];
server.listen(8000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.on('new user', function(data, callback){
if (nicknames.indexOf(data) != -1){
callback(false);
} else{
callback(true);
socket.nickname = data;
nicknames.push(socket.nickname);
updateNicknames();
}
});
function updateNicknames(){
io.sockets.emit('usernames', nicknames);
}
socket.on('send message', function(data){
io.sockets.emit('new message', {msg: data, nick: socket.nickname});
});
socket.on('disconnect', function(data){
if(!socket.nickname) return;
nicknames.splice(nicknames.indexOf(socket.nickname), 1);
updateNicknames();
});
})
;
You can use the broadcast function. This will broadcast to every other socket except the one that send the broadcast.
socket.on('disconnect', function () {
socket.broadcast.emit('leave',{name:name});
});
socket.on('leave', function (msg) {
//Add msg that msg.name is leaving
});
Events binding for socket are moved to separate module:
exports.bind = function(socket) {
socket.on('join', function(data) {
socket.join(data.type);
});
socket.on('message', function(data) {
global.io.sockets.in('rooma').emit('message', data);
});
}
server.js:
var app = express();
//creating socket server
server = http.createServer(app);
io = global.io = require('socket.io').listen(server, {'log level': 3});
io.sockets.on('connection', function(socket) {
//binding events on socket
events.bind(socket, io);
});
The problem is, that message is never sent to the clients in 'rooma'. But if i emit it global:
global.io.sockets.emit('message', data);
It works. Where can be problem? I've tested the client belongs to room for sure.
this works when you get the initialisation of the event from the room to which you like to send your message:
exports.bind = function(socket) {
socket.on('join', function(data) {
socket.join(data.type);
});
socket.on('message', function(data) {
socket.get('room', function (error, room) {
io.sockets.in(room).emit('message', data);
});
});
}
I'm trying an example of WebSocket to develop a simple chat.
server.js:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/test.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
and test.html:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('connect', function() {
alert('<li>Connected to the server.</li>');
});
socket.on('message', function(message) {
alert(message);
});
socket.on('disconnect', function() {
alert('<li>Disconnected from the server.</li>');
});
function sendF(){
var message = "Test";
socket.send(message);
alert('Test Send');
}
In test.html I have also a simple button that onClick call sendF.
If I try it I see on my browser an alert when I CONNECT, SEND, and DISCONNCT, and if I check in console, I see the message.
But I cannot receive the same message in response from server, to show it in my browser! I think socket.on('message'... is not working for me!
Your server.js is missing event listeners. It's also missing where you are doing the send of the message to be displayed in the browser.
io.sockets.on('connection', function (socket) {
console.log('user connected');
socket.send('hello world');
socket.on('disconnect', function () {
console.log('user disconnected.');
});
socket.on('message', function (data) {
console.log(data);
});
});