Socket.IO & Node/Express Configuration - javascript

I am trying to connect my front-end which is on a online text editor to my Node server. I am hitting network error strict-origin-when-cross-origin and it is not hitting the Socket IO listener. Please let me know what is causing this error & how to fix it. Thanks!
Here is the Node.js code:
const cors = require('cors');
const app = express();
app.options('*', cors())
app.all('*', function(req, res) {
res.send("Oops, incorrect URL")
});
const server = http.createServer(app).listen(process.env.PORT, () => {
console.log('Express server listening on port 1337');
});
var io = require('socket.io')(server);
io.set('origins', '*:*');
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
console.log("CONNECTED!")
});
Here is the front-end:
import io from 'socket.io-client'
var socket = io('https://myserver.com/', {secure: true});
socket.emit('chat message', "testing");

Related

Is there a way to host a Socket.Js server on Github?

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/chat.html');
});
server.listen(8000, () => {
console.log('listening on *:8000');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
});
io.emit('some event', { someProperty: 'some value', otherProperty: 'other value' }); // This will emit the event to all connected sockets
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
Currently it's localhost, and I have to run node index.js everytime I want to start it. But is there a way I can host it on GitHub so it always stays on?
Short answer: No.
GitHub hosts git repositories containing code, but doesn't run code. GitHub pages can serve static sites, but cannot run server side code, which include node.js and express. If you want to host something like this for free, I suggest looking into Heroku.

Using socket io with express and ejs

Hey so i just started to learn node js today and i am using express with ejs and trying to add a socket io server / chat but i can't seem to work out why i can't get it to work.
The page loads but does not connect to the socket server.
server.js:
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const app = express();
// EJS
app.use(expressLayouts);
app.use(express.static("public"));
app.set('view engine', 'ejs');
// Routes
app.use('/', require('./routes/index.js'));
app.use('/chat', require('./routes/chat.js'));
app.use((req, res, next) => res.redirect('/'));
const listener = app.listen(process.env.PORT, () => {
console.log('Your app is listening on port ' + listener.address().port)
});
routers/chat.js
const express = require('express');
const router = express.Router();
const server = require('http').createServer();
const io = require('socket.io')(server);
// Chat Page
router.get('/chat', (req, res) => {
res.render("chat/chat");
});
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('chat message', function(msg) {
console.log('message: ' + msg);
});
});
module.exports = router;
views/chat/chat.ejs:
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
Error:
Uncaught ReferenceError: io is not defined
You cannot source /socket-lib/socket.io.js,
you must source http://yourwebsite.com:12345/socket.io/socket.io.js.
bascily, you'll need to provide full source for the server adress.
The server automatically does the rest for you.
Source: https://stackoverflow.com/a/12160485/3010171
also. you might try out ./socket-lib/socket.io.js with a . before the slash

node.js not printing to console

I am trying to use sockets in my api. However I could not see the logs in the console.
The only output I see is:
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
We are live on8000
Here is my server.js file:
// server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
var server = require('http').createServer(app);
var io = require('socket.io')(server);
const db = require('./config/db');
app.use(express.static(__dirname + '/../app'));
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url,(err,database) =>{
if (err) return console.log(err);
//check below line changed
require('./app/routes')(app, database);
app.listen(port,() => {
console.log("We are live on"+port);
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection',function(socket){
console.log('client connected');
socket.on('disconnect', function () {
console.log('disconnect');
});
});
})
and the index.html is:
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
<body>Hello world</body>
</html>
I see Hello world on the web browser, but I could not see 'client connected' on the console log.
Update: In your browser client you can see error in console.log http://localhost:8000/socket.io/socket.io.js 404 and (index):6 Uncaught ReferenceError: io is not defined
You have attach socket handler to a http server var io = require('socket.io')(server);, but in your code you start web server by express server
app.listen(port,() => {
console.log("We are live on"+port);
});
change it to
server.listen(port,() => {
console.log("We are live on"+port);
});
I have created a new .js file and listening to port 3000 instead of 8000 worked for socket.io
appsocket.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
//Whenever someone connects this gets executed
io.on('connection', function(socket){
console.log('A user connected');
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Now I am able to see the logs on console when I call localhost:3000 instead of localhost:8000

WebSocket connection closes when server sends message only on port 80

I have a simple, local Nodejs server running Express. I'm using express-ws to set up a WebSocket endpoint. The client sends messages fine, and the server receives them, but when the server tries to send a message back, the connection closes and the client never receives the message.
This only happens over port 80. The connection stays open over port 3000, 8080, 443, and the client receives the messages the server sends back.
app.js
const express = require('express');
const path = require('path');
const app = express();
const expressWs = require('express-ws')(app);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next){
res.send(`<script src="js/client.js"></script>`);
});
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
ws.send(msg); //The connection doesn't close with this commented out
});
});
app.listen(80);
client.js
const ws = new WebSocket(`ws://${window.location.host}`);
ws.onopen = function(e){
console.log("WebSocket connected");
ws.send("testing 1");
ws.send("testing 2");
}
ws.onmessage = function(msg){
console.log(msg);
}
I'm at a loss. Any help would be appreciated.

Express nodejs socket.io with cordova

I'm trying to implement socket.io on my server. This server is an API (express nodejs).
The server side is simple, but for the client side I'm using phonegap/cordova.
I don't use a phone to test what I do, I use my browser (chrome).
Si this the server side :
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
for now, this is simple,
But for the client side I am completely confuse (cordova phonegap),
This is what I have :
index.html
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
console.log('send')
socket.emit('my other event', { my: 'data' });
});
</script>
Nothing appears but errors like
GET http://localhost:8080/socket.io/?EIO=2&transport=polling&t=1462638049681-3 net::ERR_CONNECTION_REFUSED
and nothing on my server
any ideas to help me ? thanks :)
Your server is not listening on port 8080. That's why when you try to connect from browser to var socket = io.connect('http://localhost:8080');, it shows 'Connection Refused'.
This edit would work for you.
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
//Now server would listen on port 8080 for new connection
http.listen(8080, function(){
console.log('listening on *:8080');
});

Categories