NodeJS SockeIO basic problem with emitting - javascript

So I'm trying to build a chat application with SocketIO. However, I don't understand most of the code in the SocketIO tutorial, specifically the JQuery parts. I'm just not familiar. I thought it wouldn't be too hard, but I've hit a wall on the emit() function. My script seems to work up till that point.
Here is the client code
script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
const chatbox = document.getElementById('n');
const d = document.getElementById('m');
function sender(){
var message = chatbox.value;
socket.emit('chat message',message);
}
socket.on('chat message', (msg) => {
d.appendChild($('<div>').text(msg));
});
const b = document.querySelector('#clicker');
b.addEventListener('click',sender);
</script>
and here is the relevant server code
io.on('connection', (socket) => {
console.log('Connection logged');
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
Not sure why the emit fails in the client. Any help would be appreciated.

For anyone watching, I figured it out by rewriting the existing working SocketIO code into my own. Here's the solution
Client side
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const chatbox = document.getElementById('n');
const d = document.getElementById('messages');
function sender(){
var message = chatbox.textContent;
socket.emit('chat message',message);
}
socket.on('chat message', (msg) => {
const t = document.createElement('li');
t.textContent = msg;
d.appendChild(t);
});
const b = document.querySelector('#clicker');
b.addEventListener('click',sender);
</script>
and server
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});

Related

Socket.io - TypeError: socket.in is not a function

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

Socket only emits once

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.

Socket.io rooms is sending to everybody, not just single room

I have no idea why this won't work; here's my code:
io.on('connection', function(socket) {
socket.on('join', function(data) {
socket.join(data.email); // We are using room of socket io
User.findById(bid.highestBidder, (err, theUser) => {
io.sockets.in(theUser.email).emit('outbid', {msg: 'You have been outbid!'});
});
});
});
Now, here's the code on the client-side javascript:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var userEmail = $("#userEmail").val();
socket.emit('join', {
email: userEmail
});
socket.on("outbid", function(data) {
console.log(data);
});
</script>
If you need me to paste more code, let me know and I will.
Basically, when the socket function gets executed, it's sending it to every browser instead of just the room with the "email."
io.on('connection', function(socket){
socket.join('room name');
});
io.to('room name').emit('some event');

Cant retrieve simple broadcast message in the HTML file using NodeJS/Socket.io

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 :-)
});

Pass string value in socket.io

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...

Categories

Resources