Socket.io: emit from client does not work - javascript

I'm trying to emit an event on the client, but the server does not respond at all. A message does not appear in the console ('Received!'), the following event is not initiated. The event must emit when the button is clicked. Other actions, such as outputting a message to the console, work fine, but the event does not start. What is the problem? Сonnection events work properly.
Server:
class ChatHandlers {
constructor() {
this.names = {};
this.connection = this.connection.bind(this);
this.send = this.send.bind(this);
this.message = this.message.bind(this);
}
connection(socket) {
socket.emit('new_user', {
name: 'Example name'
});
}
send(socket) {
console.log('Received!');
var ip = socket.handshake.address;
io.sockets.emit('message', {
name: ip,
message: socket.message
});
}
message(socket) {
console.log('Success!');
}
}
var handlers = new ChatHandlers();
io.on('connection', handlers.connection);
io.on('send', handlers.send);
Client:
var socket = io.connect('http://localhost:8080/');
socket.on('connect', function (data) {
socket.on('new_user', function (data) {
console.log(data.name);
});
socket.on('message', function (data) {
console.log(data);
});
$('#send').click(function() {
socket.emit('send', {
message: $('#mess').val()
});
$('#mess').val('');
});

Related

Unable to broadcast multiple messages on socket io

I'm writing a program where I want to broadcast messages using socket IO. This is for a chat interface.
Here is my code
socket.on('send-chatMessage', message => {
var gotNewMsg = false;
sendChatMessage(message, chatMessagesJSON, function (resp, err) {
console.log('resp from send chat --->');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
gotNewMsg = true;
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
if (gotNewMsg) {
buildChatResponse(chatMessagesJSON, function (resp, err) {
console.log('resp from send chat');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
socket.broadcast.emit('chat-message', {
message: JSON.stringify(resp.messages[0].type),
name: 'Agent'
});
});
}
})
});
Here My first
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
is working fine but my second one
if (gotNewMsg) {
buildChatResponse(chatMessagesJSON, function (resp, err) {
console.log('resp from send chat');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
socket.broadcast.emit('chat-message', {
message: JSON.stringify(resp.messages[0].type),
name: 'Agent'
});
});
}
is not working as expected. I'm able to enter the if and also print the result. The only thing failing is broadcasting.
Here is my broadcast handlers.
socket.on('chat-message', data => {
appendMessage(`${data.name}: ${data.message}`);
})
function appendMessage(message) {
const messageElement = document.createElement('div');
messageElement.innerText = message;
messageContainer.append(messageElement);
};
please let me know where am I going wrong.

Socket.io Rooms

In below program, cashier.js call join_session/room in server, every time it emits cart_items, then the server will emit it to all client in that specific room. So the question is this the right way to do it, do i really need to call join_session/room in my cashier.js every time it emits data?
server.js
let nsp = io.of('namespace_name');
let session;
nsp.on('connection', function (socket) {
socket.on('join_session', function (client_ip) {
session = client_ip;
socket.join(session);
console.log('New session (' + session + ')');
socket.on('cart_items', function (data) {
console.log(session);
console.log(data);
nsp.to(session).emit("cart_items", data);
});
});
});
cashier.js
socket.on('connect', function () {
socket.emit('join_session', session);
socket.emit('cart_items', { name: item.name, price: item.price });
});
customer.js
socket.on('connect', function () {
socket.emit('join_session', session);
socket.on('cart_items', function (data) {
console.log(data);
});
});
FYI when i try to do this in my cashier.js
socket.on('connect', function () {
socket.emit('join_session', session);
});
//on button click
socket.emit('cart_items', { name: item.name, price: item.price });
There were times that client 1 sends data to client 2 and vice versa.

jquery.js: Uncaught ReferenceError: connect is not defined

I run this code on a website with a database, this interacts with the ambiance.js , jquery.js (3.2.1) and socket.js but I believe this requires some other dependency that I omitted.
var SOCKET = null;
var user = null;
$(document).ready(function() {
connect();
});
function request(msg)
{
var m=msg;
if(m.type == 'aMessage')
{
console.log(m.msg);
}
function connect()
{
if(!SOCKET)
{
var hash = getCookie('hash');
if (hash == '')
{
$.ambiance({message: 'Please login!'});
}
else
{
$.ambiance({message: 'Connecting to server..', type: 'success'});
}
SOCKET = io(':4095');
SOCKET.on('connect', function(msg)
{
if(hash != '')
{
$.ambiance({message: 'Connected', type: 'success'});
}
SOCKET.emit('hash', {
hash: hash
});
});
SOCKET.on('connect_error', function(msg){
$.ambiance({message: 'Connection lost', type: 'error'});
});
SOCKET.on('request', function(msg){
request(msg);
});
}
}
}
Actually, you created the connect() function inside the request function (which wasn't called yet):
Just move it outside and it should work.

Pusher: Cannot broadcast client event

I'm developing a conference app with laravel 5 and I decide to implement a webRTC solution for that. So, I use Pusher for signaling stuff, but I have a prob: I'm using SimplePeerJs for the webRTC things, when I trigger an event (after subscribing and others stuff), I have the following err:
Pusher : Error : {"type":"WebSocketError","error":{"type":"PusherError","data":{"code":null,"message":"Cannot broadcast client event (connection not subscribed to channel presence-chat)"}}}.
my code is:
Pusher.log = function(message) {
if (window.console && window.console.log)
{
window.console.log(message);
}
};
var currentUser = {
nom: '{{ auth()->user()->first_name }}',
id: {{ auth()->user()->id }},
stream: undefined
};
var pusher = new Pusher('my_app_key', {
authEndpoint: 'pusher/auth',
auth: {
headers: {
'X-CSRF-Token': '{{ csrf_token() }}'
},
params: {
name: currentUser.name,
id: currentUser.id
}
}
});
var channel = pusher.subscribe('presence-chat');
var callback = function() {
console.log('Channel members:', channel.members);
};
//
channel.bind('pusher:subscription_succeeded', callback);
channel.bind('pusher:subscription_error', function(PusherError){
console.log(PusherError);
});
channel.bind('pusher:member_added', function(){
console.log('Member Added');
});
channel.bind('pusher:member_removed', function(){
console.log('Member Removed');
});
//peers stuff
var peer = new SimplePeer({ initiator: true });
peer.on('signal', function (data) {
channel.trigger('client-signal-' + currentUser.id,
{
userId: currentUser.id,
data: data
});
});
peer.on('ready', function () {
peer.send('hey peer, how is it going?')
});
any ideas?
thanks.
The issue is that the Pusher client hasn't had a chance to connect and subscribe to the channel before the peer.on('signal') is being triggered. Did you try moving the peers stuff into the subscription callback ?
var callback = function() {
console.log('Channel members:', channel.members);
//peers stuff
var peer = new SimplePeer({ initiator: true });
peer.on('signal', function (data) {
channel.trigger('client-signal-' + currentUser.id,
{
userId: currentUser.id,
data: data
});
});
peer.on('ready', function () {
peer.send('hey peer, how is it going?')
});
});

socket.io javascript don't work

Anybody an idea why this doesn't work ?
function startServer() {
console.log('function start');
var keyBool = false;
var client = require('socket.io').listen(3000).sockets;
client.on('connection', function (socket) {
console.log('someone connected');
socket.on('party', function (party) {
console.log(party);
console.log('testbla');
});
});
}
the client side:
function client() {
var party = 'test';
var server = "http://127.0.0.1:3000";
try {
var socket = io.connect(server);
} catch (e) {
alert('failed to connect');
}
//setInterval(function () { sendCoordinates }, 125);
//setInterval(function () { sendParty }, 5000);
if (socket !== undefined) {
alert('ok');
try {
socket.emit('party', {
party: 'test'
});
alert('sended...');
} catch (e) {
alert('failed with reason: ' + e);
}
}
}
When I run the server and client logs 'someone connected', but not the party object I send...
Client is an chrome extension and the server a node.js 'file'.
I don't think using some of that code is needed, other than that have you port forwarded?
if (socket !== undefined) {
alert('ok');
try {
Works for me.
$ node server.js
function start
someone connected
{ party: 'test' }
testbla
Maybe you expect the object to be sent before 'ok' is pressed on alert('sended...');..?
alert() is not the best option for debug.
$ node -v
v5.3.0
"socket.io": "^1.3.7"

Categories

Resources