I have been looking into this Socket.io MVC node.js but I'm currently struggling.
It says in the documentation:
Socket.io API's
Since Socket.MVC is just a wrapping mechanism for Socket.io, all of
the same API's can be used using the Socket.MVC module. Please see a
list of all of the API's available by visiting the Socket.io Github
page, or http://socket.io (depending on your version)
My problem is that I cant find a way to emit socket MVC to a room.
socketMVC.to(userid).emit('message', {message:2});
Should work, but it doesn't. Any idea how I can accomplish this?
EDIT:
userid is same as assigned here:
import * as io from 'socket.io-client';
download
oninit:
this.socket = io(this.socketurl);
var privateRoom = socket.request.session.passport.user;
socket.join(privateRoom);
this.socket.on('message', (data) => {
// this.messagesCounter = this.messagesCounter + 1;
alert("OMG?");
});
edit , in server.js
io.on('connection',function(socket) {
console.log('user connected');
OnlineUsers.push(socket);
// socket.join('');
console.log(socket.request.session.passport);
console.log("user is connceted");
socketMVC.init(io, socket, {
debug: true,
filePath: ['./src/routes/sockets.js']
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('add-message',function (message) {
io.emit('message', {type:'new-message', text: message});
});
socket.on('myevent', function(someData) {
console.log("MYEVENT WORKS???????");
});
});
sockets.js
var path = require('path');
module.exports = function (socket) {
var privateRoom = socket.request.session.passport.user;
socket.join(privateRoom);
socket.on('testing', function() {
console.log('GOT SOME SORT OF RESPONSE!!!');
});
};
Replace socketMVC.to by socketMVC.io.to.
Related
I'm actually trying to make a real-time connection between two different apps. I've found a bunch of tutorials about how to make a chat using socket.io, but that doesn't really help me since it's just the same app duplicated in multiple windows.
I'm making a pick & ban overlay for League of Legends in local development. My first thought was to display the empty overlay on one hand and create an interface to manually update it on the other hand. Socket.io seems to be the right thing to use in my case since it can provide new data without having to reload the component.
This is what I wrote in both apps :
const express = require('express');
const socket = require('socket.io');
// App setup
const app = express();
const server = app.listen(4200, function () {
console.log('Listening to requests on port 4200')
});
// Static files
app.use(express.static('public'));
// Socket setup
const io = socket(server);
io.on('connection', function (socket) {
console.log('Made socket connection', socket.id);
socket.on('change', function (data) {
io.sockets.emit('change', data);
});
});
But I fail to connect them as they have to listen to the same port. What am I doing wrong?
(Forgive my bad English and lack of syntax, I'm doing my best here. :p)
I am certainly not an expert on network programming, but as far as I know you need to have one listening app (backend) and another one to connect to it (client). And you define what happens with all the data (messages) that backend recieves (for example sending the messages it recieves to all the clients in the same chat room).
If I am correct to assume you are trying to connect two listening apps?
simple google search of "nodejs socket server client example" revealed this https://www.dev2qa.com/node-js-tcp-socket-client-server-example/ might wanna take your research in this direction
u can try something like this way
var express = require('express');
var socket = require('socket.io');
// App setup
var app = express();
var server = app.listen(8080, () => {
console.log('App started')
})
// Static file
app.use(express.static('public'))
// Socket SetUp
var io = socket(server);
io.on('connection', socket => {
console.log('made the connection')
socket.on('chat',data => {
io.sockets.emit('chat',data)
});
socket.on('typing',data => {
socket.broadcast.emit('typing',data);
});
})
create another file and
var socket = io.connect('http://localhost:8080')
// Elenment
var message = document.getElementById('message');
handle = document.getElementById('handle');
btn = document.getElementById('send');
output = document.getElementById('output');
feedback = document.getElementById('feedback');
// Emit Events
btn.addEventListener('click', () => {
socket.emit('chat', {
message: message.value,
handle: handle.value
})
})
message.addEventListener('keypress', () => {
socket.emit('typing', handle.value)
})
socket.on('chat',data => {
feedback.innerHTML = '';
output.innerHTML += '<p><strong>' + data.handle +': </strong>' +
data.message + '</p>'
})
socket.on('typing', data => {
feedback.innerHTML = '<p><emp>' + data + ' is typing a message... </emp></p>'
})
details are given here node socket chat app
Ok, figured it out. Here's how it works using express and vue together :
First, setup socket.io in your express server js file :
const express = require('express')
const { Server } = require('socket.io')
const http = require('http')
const app = express()
const server = http.createServer(app)
const io = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST', 'REMOVE']
}
})
const PORT = process.env.PORT || 8080
io.on('connection', (socket) => {
console.log('New socket user')
socket.on('SEND_MESSAGE', data => {
console.log('received message in back')
io.emit('MESSAGE', data)
})
})
server.listen(PORT, () => { console.log(`Server started on port : ${PORT}`)})
As you can see we received from the client "SEND_MESSAGE" and we trigger MESSAGE from the server to forward the information to all the clients. The point I was missing is that we bind SEND_MESSAGE on the socked created from the connection but we emit from the io server.
Now you vue part :
import io from 'socket.io-client'
export default {
data() {
return {
messages: [],
inputMessage: null,
socket: io('http://localhost:8080')
}
},
mounted() {
this.socket.on('MESSAGE', data => {
this.messages.push(data)
})
},
methods: {
sendMessage() {
const message = {
senderID: this.myID,
message: this.inputMessage,
sendAt: new Date()
}
this.socket.emit('SEND_MESSAGE', message)
this.inputMessage = null
},
},
}
I have a Node/Vue application. I am consuming a WebSocket from Binance, a crypto exchange. I can see the quotes on the server console as I log them, I can send them to the browser for a short period of time before the client stops logging them.
Browser just using WebSocket API
Node using ws library
Node code, this I am running as it's own service as its just this.
'use strict';
const WebSocket = require('ws');
const binanceWS = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade')
const server = new WebSocket.Server({ port: 5002 });
//websocket connection event will return a socket you can later use
binanceWS.on("open", function() {
console.log("connected to Binance");
});
binanceWS.on('message', function(data){
console.log(data);
server.on('connection', function connection(ws){
console.log("Connected a new client");
ws.send(data);
});
server.on('closed', function (id){
console.log("connection closed");
console.log(id);
});
server.on('error', function (err){
console.log(err)
})
})
On the Client side I am using Vue and in the app.js file I have this on the created hook.
let socket = new WebSocket("ws://localhost:5002")
socket.addEventListener('message', function(event){
let quotes = JSON.parse(event.data);
console.log(quotes.p)
});
socket.addEventListener('error', function(event){
console.log("closing because " + event);
})
Right now I am only listening to the consoles in the above app.vue file.
What I see in the browser console is a lot of quotes, then they stop after a second or 2. There can be over a thousand quotes in some times. Then on occasion I see a console.log('created') that I have in a child component of app.vue. In many cases this is the last thing in the console after hundreds of quotes.
In the console.log for the server I see a lot of sessions being created with one page refresh. So much that it fills my console.
So I'm not sure I am creating the connections correcly, I am not sure if Vue is somehow stopping the console.log's?
I don't see any errors anywhere and the entire time in my server console the Binance API continues streaming.
you have to write server event listener outside binance on message handler;
then you can pass messages from binance to the server by emitting new event to the server
on receiving message from binance you can send data to all connection on the server
Or Try this code I think it will work :
'use strict';
const WebSocket = require('ws');
const binanceWS = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade')
const server = new WebSocket.Server({ port: 5002 });
server.on('connection', function connection(ws){
console.log("Connected a new client");
});
server.on('closed', function (id){
console.log("connection closed");
console.log(id);
});
server.on('error', function (err){
console.log(err)
})
//websocket connection event will return a socket you can later use
binanceWS.on("open", function() {
console.log("connected to Binance");
});
binanceWS.on('message', function(data){
console.log(data);
server.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
})
I've the following hierarchy: Store -> Manager -> Assistant
A Manager can access everything sent by Assistant, the Assistant can only access what the Manager specifically provides.
As far as I understood I could create namespaces or rooms, e.g. named manager_assistant1, manager_assistant2, etc.
Result: Assistant (id: 1) listens to manager_assistant1. That's fine. But what about the Manager? Is it possible to listen to manager_*?
My current client just listens to the stream and outputs data which was sent to or from it. That's bad.
Server
var server = require('http').createServer();
var io = require('socket.io')(server);
io.on('connection', function(client){
client.on('myEvent', function(data) {
// do something with the data
// ...
// return the modified data
io.emit('myEvent', data);
});
});
server.listen(3000, function(){
console.log('listening on port 3000');
});
Client
var socket = io.connect('http://example.com:3000/');
socket.emit('myEvent', {
from: 'assistant1',
to: 'manager',
key: 'value'
});
socket.on('myEvent', function(data) {
var user = 'assistant1'; // or 'manager', 'assistant2', ...
if (data.from == user || data.to == user) {
console.log(data.key);
}
});
Any ideas? Thanks in advance!
You could create some logic in more high level, using channels and try to send your bussiness data in json eg.
Try to look in package like that
https://www.npmjs.com/package/sockjs-rooms
I think what I need to do is reset Socket.io entirely after each test using socket.io.
Any ideas? Here's what I'm doing:
I have a test using Socket.IO's Client library, an angular service (github.com/chrisenytc/ng-socket), requireJS, and a local test server. When using karma's watch feature, it runs fine the first time, but fails subsequent attempts (event listeners aren't triggered, debug logging shows an 'xhr poll error').
the simple version of the test is (full version):
define(['services/serviceModule', 'angular-mocks'], function() {
describe('ILC Server Services', function() {
var socket;
beforeEach(module('ignisLibriColloqui.services', function(Config, $socketProvider) {
$socketProvider.setUrl(Config.ilcTestServerUrl);
Config.ilcServerUrl = Config.ilcTestServerUrl;
url = Config.ilcTestServerUrl;
}));
beforeEach(inject(function(ILCServerService, $socket) {
ilcServerService = ILCServerService;
socket = $socket;
}));
it('expects emit(\'ping\') to trigger on(\'pong\')', function(done) {
socket.emit('ping',{})
socket.on('pong',function(data) {
done();
});
});
});
});
and the simple server is (full version)
var httpPort = 10999;
var socketPort = 5001;
var restify = require('restify');
var socketio = require('socket.io')(socketPort);
var fs = require('fs');
var server = restify.createServer({
name: 'ilcServer Mock'
});
var io = socketio.listen(server);
server.get(/.*/, restify.serveStatic({
'directory': __dirname,
'default': './app/index.html',
'maxAge': 0
}));
io.sockets.on('connection', function(socket) {
var socketId = socket.id;
console.log('user connected');
socket.on('ping', function(data) {
console.log('ping');
socket.emit('pong', data);
});
socket.on('disconnect',function() {
console.log('disconnect');
socket.disconnect();
});
});
server.listen(httpPort, function() {
console.log('restify server listening at %s', server.url, 'socket port:', socketPort);
});
Edit
After carefully exploring the connections using the logging described by the Socket.io docs it has become clear to me that disconnecting the client is not enough. The client logs the "pong" events without firing the socket.on('pong',event), even when using an afterEach to cause socket.disconnect() and socket.io.connect(function(){done()}) to trigger, the new calls to socket.emit are not triggered.
I have this code running in
Client side:
$(function(){
var iosocket = io.connect();
iosocket.on('connect', function () {
$('#incomingChatMessages').append($('<li>Connected</li>'));
iosocket.on('message', function(message) {
$('#incomingChatMessages').append($('<li></li>').text(message));
});
iosocket.on('disconnect', function() {
$('#incomingChatMessages').append('<li>Disconnected</li>');
});
});
$('#outgoingChatMessage').keypress(function(event) {
if(event.which == 13) {
event.preventDefault();
iosocket.send($('#outgoingChatMessage').val());
$('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val()));
$('#outgoingChatMessage').val('');
}
});
});
Server Side
var fs = require('fs'), http = require('http'), socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(8080, function() {
console.log('Listening at: localhost');
});
socketio.listen(server).on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
Question :
How can I include the getUserMedia and other WEBRTC API's to create a simple video application ?
Have you looked at, or found, an opensource code set named webrtc.io. If you look at the example code (in the webrtc.io-demo project), you will find a really good example of how to use the getusermedia and peerconnection API's. This code does implement node.js but websocket.io instead of socket.io. I do not know that much about either, so I am not sure if there exists any compatibility between them.