Hi I am trying to setup a connection with socket.IO but not able to do so. At present I am not getting any error but the connection is not taking place.Please find below the relevant details :
app.js
const express = require('express');
require('./db/mongoose');
const functions = require("firebase-functions");
var bodyParser = require('body-parser');
const app = express();
const http = require('http').createServer(app);
var io = require('socket.io');
socket = io(http, {cors: {
origin: "http://localhost",
methods: ["GET", "POST"]
}
});
var cors = require("cors");
var cookieParser = require('cookie-parser');
var path = require('path');
app.use(cors());
const portCheck = process.env.PORT || 3001
socket.on('connection', function (socket) {
console.log('connected to socket');
socket.emit('greeting-from-server', {
greeting: 'Hello Client'
});
});
app.listen(portCheck, ()=> {
console.log('Server Listening to port:' + portCheck);
})
Changes should done for your code as follows:
Change app listen with server listen
wrap socket.on(//...) with io.on(//...)
replace this lines
const app = express();const http =
require('http').createServer(app);
with
var server = require('http').Server(app);
var io = require('socket.io')(server);
After the changes code is like follows.
const express = require('express');
require('./db/mongoose');
const functions = require("firebase-functions");
var bodyParser = require('body-parser');
const app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
socket = io(http, {cors: {
origin: "http://localhost",
methods: ["GET", "POST"]
}
});
var cors = require("cors");
var cookieParser = require('cookie-parser');
var path = require('path');
app.use(cors());
const portCheck = process.env.PORT || 3001
server.listen(portCheck, ()=> {
console.log('Server Listening to port:' + portCheck);
})
io.on('connection', (socket)=> {
socket.on('connection', function (socket) {
console.log('connected to socket');
socket.emit('greeting-from-server', {
greeting: 'Hello Client'
});
});
});
follow more information through this link. https://socket.io/get-started/chat.
Related
I Have code like this.
const pino = require('pino')
const { Boom } = require('#hapi/boom')
const fs = require('fs')
const chalk = require('chalk')
require('dotenv/config')
const express = require('express')
const socket = require("socket.io");
const { toDataURL } = require('qrcode')
const mysql = require('mysql');
require('dotenv').config();
const request = require('request');
const { smsg } = require('./app_node/lib/myf')
const app = express()
const host = process.env.HOST
const port = parseInt(process.env.PORT)
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
const ser = app.listen(port, host, () => {
console.log(`Server is listening on http://${host}:${port}`)
})
const io = socket(ser);
how do i get my code to run on the https server
i want to run my server in https in nodejs
My problem is that socket.emit is taking so much time to send the data to the server, i have tried anything but i got no results, this is the code:
Client side
$( "#mensaje" ).keypress(function( event ) {
if ( event.which == 13 ) {
$('.botonEnviarMensaje').click();
}
});
$('.botonEnviarMensaje').click(function(){
var myInput = document.getElementById("mensaje");
if(!isEmpty(myInput.value)){
socket.emit('newMessage',dataPerson,myInput.value)
console.log("envie un mensaje")
}
$('#mensaje').val('');
})
Server side
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 3000;
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const util = require('util')
app.use('/',express.static(path.resolve(__dirname, '../../public')));
app.get('/',(req,res)=>{
res.sendFile(path.resolve(__dirname + '/../../public/Login/index.html'))
})
io.on('connection', function(socket){
console.log('a user connected');
socket.on('newMessage',function(data,value){
console.log("llego un mensaje")
io.sockets.emit('messageAll',data,value);
})
});
I'm trying to use socket Io in my server and when I try to acessas the service was I create the browser its given this error:
ERR_SSL_VERSION_OR_CIPHER_MISMATCH
Here is my server code:
'use strict';
const chalk = require('chalk');
const _ = require('lodash');
const fs = require('fs');
let options = {
key: fs.readFileSync("privkey.pem"),
cert: fs.readFileSync("cert.pem")
};
const app = require('express')(options);
const https = require('https').Server(app);
const io = require('socket.io')(https,{origins:'*:*'});
const bodyParser = require('body-parser');
const multer = require('multer'); // v1.0.5
const upload = multer(); // for parsing multipart/form-data
const sockets = {};
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
https.listen(3002, function () {
console.log(chalk.yellow("Serviço rodando na porta 3002"));
});
io.on('connection', function (socket) {
console.log(chalk.green("Cliente Conectado"));
sockets[socket.id] = socket;
socket.on('disconnect', function () {
console.log(chalk.red("Cliente Disconectado"));
delete sockets[socket.id];
});
});
app.post('/atualizador', upload.array(), function (req, res) {
_.each(sockets,function(socket,idSocket){
console.log(idSocket);
socket.emit('posicao',req.body);
});
res.send('Atualizador ON');
});
And here is the client code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script>
const socket = io('https://localhost:3002/');
socket.on('posicao', function(msg){
console.log(msg);
});
</script>
This certs and privatekey already is used on my domain and why is not working on socket.io and express?
You should pass nothing to express and options and app to https.Server:
const app = require('express')();
const https = require('https').Server(options, app);
I have an express router defined for express-ws npm package. The router looks is exported like:
//ws.js
var express = require('express');
var router = express.Router();
var connections = {};
router.ws('/connect/', function (ws, req) {
// console.log(ws);
ws.on('close', function(x, y, z) {
console.log(a, b, c);
});
});
module.exports = router;
The (not all) statements in the express app are (and in order):
//app.js
var app = express();
var expressWs = require('express-ws')(app);
var index = require('./routes/index');
var ws = require('./routes/ws');
...
...
app.use('/ws', ws);
app.use('/*', index);
The server has statements like:
//bin/www - Generated by express generator
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
After I run it, I am not able to connect to /ws route over websocket. Am I missing something here? Is there a better way to create websocket running on Express 4?
This is the error I see at the client! What am I doing wrong?
changes to app.js
var app = express();
var server = require('http').Server(app);
var expressWs = require('express-ws')(app,server);
...
...
//module.exports = app;
module.exports = {app: app,server: server};
changes to bin/www
//var app = require('../app');
var app = require('../app').app;
...
...
//var server = http.createServer(app);
var server = require('../app').server;
I know this is old but here's the issue. HTTP server isn't required.
//app.js
const express = require('express');
const { app } = require('express-ws')(express());
const index = require('./routes/index');
const ws = require('./routes/ws');
...
app.use('/ws', ws);
app.use('/*', index);
...
app.listen(8080, () => console.log('Listening on port: 8080');
I would like to use socket.io and express routes and I have the following code:
app.js
var
http = require('http'),
path = require('path'),
passport = require('passport'),
userpassport = require('./lib/strategies/local'),
githubpassport = require('./lib/strategies/github'),
flash = require('connect-flash'),
express = require('express'),
logger = require('morgan'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
errorhandler = require('errorhandler'),
csrf = require('csurf'),
favicon = require('serve-favicon'),
sockets = require('./lib/socket'),
app = express();
var routes = require('./routes')();
app.get('/', routes.index);
var server = http.createServer(app).listen(app.get('port'), function () {
var io = require('socket.io')(server);
io.on('connection', function (iosocket) {
sockets.setSocket(iosocket);
});
});
lib/socket.js
var socket;
exports.setSocket = function(iosocket) {
console.log('setting socket');
socket = iosocket;
}
exports.getSocket = function() {
console.log('getting socket');
return socket;
}
routes/index.js
var sockets = require('../lib/socket');
module.exports = function () {
var routes = {};
routes.index = function (req, res) {
var socket = sockets.getSocket();
socket.on('app/create', function (data) {
console.log('got app create');
});
}
This does not work, I think it's because the setSocket function that appears on app.js runs after the page was loaded, therefore when I getSocket on the route it's not the latest socket (I can console log the given socket on the route, I can see there's a socket there, but I can also see that the setSocket runs afterwards).
How can I solve this?