io.sockets.in not working in nativescript-socketio - javascript

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

Related

Socket.io broadcast.emit is not working but it works without broadcast

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

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 app does not work on phone client

I have a socket.io app that works perfectly on chrome, safari and opera, with notifications made using push.js.
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://cdn.rawgit.com/Nickersoft/push.js/master/push.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var socket = io();
var username = prompt("What's your name?");
var notification = new Audio('https://cdn.rawgit.com/InfiniaPress/Passenger-Pigeon/master/assets/notification.mp3');
if(username){
socket.emit('connection info', username);
}
function send(message) {
$('#messages').append($('<li>').text(message));
}
socket.on('user add', function(usr){
send(usr.username + " has joined.");
});
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('user left', function(usr){
send(usr.username + " has disconnected.");
})
socket.on('chat message', function(msg, usr){
Push.create('Passenger Pigeon', {
body: usr.username + ": " + msg,
icon: "https://cdn.rawgit.com/InfiniaPress/Passenger-Pigeon/master/assets/pigeon-final.png",
timeout: 4000,
onClick: function () {
window.focus();
this.close();
},
vibrate: [200, 100, 200, 100, 200, 100, 200]
});
notification.play();
send(usr.username + ": " + msg);
});
</script>
</body>
</html>
The above is my client side.
var express = require('express'); // Get the module
var app = express(); // Create express by calling the prototype in var express
var http = require('http').Server(app);
var io = require('socket.io')(http);
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
var config = require('./config.json');
app.get('/', function(req, res){
res.sendFile(__dirname + '/view/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg, {username: socket.username});
});
socket.on('connection info', function(usr){
socket.username = usr;
io.emit('user add', {username: usr});
});
});
io.on('connection', function(socket){
console.log('Passenger Pigeon >> a user connected');
socket.on('disconnect', function(){
socket.broadcast.emit('user left', {
username: socket.username,
});
console.log('Passenger Pigeon >> user disconnected');
});
});
http.listen(process.env.PORT || config.port, function(){
console.log('listening on *:' + config.port);
});
^that is my server side.
When I open the app on mobile the [username] has joined prints out, but all messages do NOT appear on the client side. Other computers receive the messages. Why is this so?

How I can get a socket.username ? (socket.io)

I want to write a simple chat for practical experience.
All right, but I can't get a socket.nickname for notice a join/leave from the room. (when I tried pass its, he always sad a 'undefined').
Now all right, tried to create list of rooms
UPDATE CODE:
client.js:
$('#roomForm').submit(function() {
socket.emit('createRoom', $('#roomName').val());
$('#roomForm').hide();
$('#chatForm').show();
return false;
});
socket.on('message', function(data) {
newMessage(data);
});
socket.on('showRooms', function(rooms) {
console.log(rooms);
for(var i = 0; i < rooms.length; i++) {
$('#rooms').append($('<li>')
.append($('<form id="freeRoom">')
.append($('<span id="room">').text(rooms[i] + ' ///'))
.append($('<button>').text('connect'))));
};
});
$('#freeRoom').submit(function() {
socket.emit('connectToRoom', $('#room').text());
return false;
});
server.js:
io.on('connection', function(socket) {
socket.on('sendNickname', function(username) {
socket.username = username;
users.push(socket.username);
socket.emit('showRooms', rooms);
});
socket.on('disconnect', function() {
socket.broadcast.to(socket.room).emit('notice', socket.username + ' has left the room');
users.splice(users.indexOf(socket.username), 1);
socket.emit('showRooms', rooms);
});
socket.on('message', function(data) {
socket.broadcast.to(socket.room).emit('message', data);
});
socket.on('createRoom', function(room) {
socket.leave(socket.room);
socket.room = room;
rooms.push(socket.room);
socket.join(socket.room);
socket.emit('showRooms', rooms);
console.log('Rooms: ' + rooms);
socket.broadcast.to(socket.room).emit('notice', socket.username + ' has joined to room');
});
socket.on('connectToRoom', function(room) {
console.log('Will connect to that room: ' + room);
socket.join(room);
});
});
**UPD 2: **
Tried to connect free created room:
$('#freeRoom').submit(function() {
socket.emit('connectToRoom', $('#room').text());
return false;
});
P.S. And... Sorry for my english >.<
The event name that you emit, that is 'connect' is reserved in Socket.io along with 'message' and 'disconnect':
http://socket.io/docs/#sending-and-receiving-events
Socket.IO allows you to emit and receive custom events. Besides
connect, message and disconnect, you can emit custom events:
...
Change it to something else, e.g:
Server.js:
io.on('connection', function(socket) {
socket.on('send-nickname', function(nickname) {
socket.nickname = nickname;
users.push(socket.nickname);
console.log(users);
});
...
Client.js
socket.emit('send-nickname', nickname);

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