The code below only emits the data only once. I am not sure it even emits it once as I believe the data is not being sent correctly from frontend(angular 2) to the backend(nodeJs).
frontend code of chat.component.ts:
ngOnInit() {
const sendData = {
username: this.username,
message: this.message
};
const socket = socketIo('http://localhost:3000');
socket.emit('chat message', {
username: 'sendData.username',
message: sendData.message
});
socket.on('chat message', function(msg){
const messageArea = document.getElementById('output');
messageArea.innerHTML +="<strong>" + socket.username + "</strong> : " + socket.message + "\n";
console.log(msg.username + 'lmemons');
});
}
the code of backend:
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg){
console.log('///////////////////////////////');
io.emit('chat message', msg.username + ': ' + msg.message);
console.log('--------------------------');
});
});
the code runs once which is shown by the console.logs. it only comes out as undefined each time.
I have tried to use the:
socket.on('chat message', function(msg){...
outside of
io.on('connection', function(socket){
but it has errors with the socket claiming that it is undefined.
Essentially I want to append the data onto every all connected sockets' text area.
I was using this https://socket.io/get-started/chat/ tutorial for help.
Related
I'm trying to send a message to everyone except the sender.
server.js
io.on('connection', (socket) => {
socket.on('typing', (msg) => {
io.broadcast.emit('typing', msg);
});
});
cleint.html
var socket = io();
socket.emit('typing', 'some message');
socket.on('typing', (msg) => {
$('#myLabel').append(msg);
});
If i remove the broadcast in server to just io.emit then it works, but the sender also sees the message.
instead of
io.broadcast.emit('typing', msg);
try
socket.broadcast.emit('typing', msg);
im trying to build a private chat system in nativescript app using socketio and nodejs for the live chat feature.
this is the plugin i use https://github.com/triniwiz/nativescript-socketio/
It works well as a group chat, but i want to make it private. so i searched and saw io.sockets.in().emit is what i'm supposed to use rather than io.emit()
this is what i tried
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('privatechatroom', function(data){
socket.join(data.chatid, function () {
io.sockets.in(data.chatid).emit('joined', { mes: 'Joined chat room' + data.chatid });
socket.on('chat message', (data) => {
console.log('message: ' + data.message);
//io.emit('chat message', );
io.sockets.in(data.chatid).emit('chat message', { message: data.message, type: data.type, date: data.date, sender: data.sender });
});
socket.on('typing', (msg) => {
console.log('message: ' + msg);
io.sockets.in(msg).emit('typing', msg);
});
socket.on('notTyping', (msg) => {
console.log('message: ' + msg);
io.sockets.in(msg).emit('noTyping', msg);
});
});
});
});
On broswer, it works well for a private chat. but on my nativescript app, it doesnt work except i use io.emit() rather than io.sockets.in()
first of all , you cant use socket.on(event...) in socket.join() section:
socket.on('privatechatroom', function(data){
socket.join(data.chatid, function () {
socket.in(data.chatid).emit('joined', { mes: 'Joined chat room' + data.chatid });
});
socket.on('chat message', (data) => {
console.log('message: ' + data.message);
//io.emit('chat message', );
socket.in(data.chatid).emit('chat message', { message: data.message, type: data.type, date: data.date, sender: data.sender });
});
socket.on('typing', (msg) => {
console.log('message: ' + msg);
socket.in(msg).emit('typing', msg);
});
socket.on('notTyping', (msg) => {
console.log('message: ' + msg);
socket.in(msg).emit('noTyping', msg);
});
});
when you join the socket client in a room you have to emmit your messages directly to that room with :
socket.to(chatid).emit('your event', {
foo:"bar"
});
I made a simple app that uses socket.io for sending messages.
Here the server code piece:
var io = require('socket.io')(http);
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('disconnect', function() {
console.log('user disconnected');
});
socket.on('connect to room', function(rooms) {
for (var i = 0; i < rooms.length; i++) {
socket.join(i);
console.log('joined to room number ' + i);
}
});
socket.on('chat message', function(id, msg) {
console.log('message!');
io.broadcast.to(id).emit('chat message', msg);
});
});
And here is the client code:
var socket = io('http://localhost:8080');
socket.on('connect', function(socket) {
console.log('you have been connected!');
});
socket.on('chat message', function(msg) {
console.log('message!');
$('#messages').append(msg);
});
socket.emit('connect to room', [{
{
user.rooms
}
}]);
if (e.which == 13 && target.is('#message')) {
var message_text = $('#message').val();
socket.in(room.id).emit(message_text);
$(#messages).append(message_text);
}
(The room object is the current opened room)
After I ran it I got an error:
Uncaught TypeError: socket.in is not a function
Have any ideas? If you think that I wrote something wrong, feel free to say it (for example x++ instead x += 1).
socket.in or socket.to not working in client and you should use it in server side.
Socket.io Documentation
for example :
io.on('connection', (socket) => {
// to one room
socket.to('others').emit('an event', { some: 'data' });
// to multiple rooms
socket.to('room1').to('room2').emit('hello');
// a private message to another socket
socket.to(/* another socket id */).emit('hey');
// WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
// named `socket.id` but the sender. Please use the classic `socket.emit()` instead.
});
It will be socket.to('some room').emit('some event');
Refer: socket-io docs
I am studying NodeJS together with Socket.io
I have a very simple chat page. But I don't know where's my error.
Here's my simple code:
index.js
var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
//res.send('<h1>Hello World</h1>');
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
//console.log('a user is connected!');
socket.on('disconnect', function() {
//console.log('user disconnected!');
});
socket.on('chat message', function(msg) {
io.emit('chat message: ' + msg);
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
index.html
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="on" /><button>Send</button>
</form>
<script type="text/javascript" src="jquery-1.12.4.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg) {
console.log(msg); //NO VALUE?
});
</script>
</body>
I can't get the value on this line:
socket.on('chat message', function(msg) {
console.log(msg); //NO VALUE?
});
The message can not be received on the client because, with
// Server: Receive and send message
socket.on('chat message', function(msg) {
io.emit('chat message: ' + msg);
}
you emit an event named chat message: ${msg}, but this is an event you are not listening on the client side.
When emitting an event you do this by defining the event name first, and then specifying the data as second parameter in JSON format. Changing the code above to
// Server: Receive and send message
socket.on('chat message', function(data) {
io.emit('chat message', { message : data.message });
}
will emit the event to the client with the message as the data. Same syntax applies, when sending the event from the client to the sever. So change
// Client: Send message
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
to
// Client: send message
$('form').submit(function() {
socket.emit('chat message', {message : $('#m').val()});
When the server answers your event, you can then receive and access the message as follows:
// Client: Receive message
socket.on('chat message', function(data) {
console.log(data.message); // VALUE :-)
});
After I am passing any string value the server is getting disconnected. The server only accept number in node.js.
io = sio.listen(server);
io.sockets.on('connection', function(socket){
socket.on('chat message', function(msg){
if ((new String(msg)).toString('utf-8') === 'utf-8') {
socket.send(msg);
console.log("Bye bye!\n");
socket.disconnect();
} else {
console.log('Received: ', msg);
messages.push(msg);
io.sockets.emit('chat message', msg);
}
});
I tried this code. But it is not working. Please help me.
var socket = io.connect('http://localhost:8000');
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val();
return false;
});
var datavar=1;
socket.on('chat message', function(msg){
$('#messages').append(msg); });
this is client side code...