Where to put socket.io server in WebStorm Express template - javascript

I am trying to add socket.io into generated express server by WebStorm. Where I am supposted to setup server and run socket.on events? Just put them all inside /bin/www, or its messy and I am supposted to make some controller like index and users page have.
PS: Also I have second fast question. Is dumb idea to have express Web server on same port as Socket.IO websocket server? I see, that all websites using subdomain to connect to socket.io, so they must be using different port.

There isn't a single answer to this. But to get some ideas of nice ways to do it, you could download some trusted examples. For example, MEAN.JS uses socket.io, and it is very structured. You may not need everything in the stack, but it's great for getting inspiration on organization. Best of luck!

I get this post to life again because i was trying to make the same thing.
I tried something and it worked !
I just followed the Socket.io doc and tried to adapt it to this template.
https://socket.io/get-started/chat
Here's what i've wrote in my www.js from the template (didn't changed anything in this file).
/**
* Create HTTP server. (This part was in by default)
*/
let server = http.createServer(app);
/**
* Try Socket io integration (This is what i've done)
*/
let io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log("yeet");
});
and here's my layout.pug
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(src='/socket.io/socket.io.js')
body
block content
script.
let socket = io();
Now when I get my page, I get the log.
Hope it can help other people.

Related

WebRTC Node.JS WebSocket Server, Block a Request if WSS Parameter is Not 1

I would like that the node Web Socket server (command: node /root/server.js) will refuse connection if PARAM is not 1. Connection like this will be refused: wss://example.com/socket.io/?**PARAM**=**0**&EIO=3&transport=websocket
server.js looks like this(EasyRTC Framework):
https://github.com/open-easyrtc/open-easyrtc/blob/master/server_example/server_ssl.js
I finally realized it's actually not that simple (doing inside server.js if PARAM != 1 then exit). Anyone can confirm this complexity or offer a simple solution, without recommending complex authentication frameworks. Also can't see that EasyRTC Framework will offer something like this.
Can someone lead me in the right direction because I am lost.
Thank you
I crawled all the EasyRTC Group, there is an authentication system for node server.js web socket and it's very simple:
var onAuthenticate = function(socket, easyrtcid, appName, username, credential, easyrtcAuthMessage, next){
// do your checks
next(null); // Run next with a null if they are allowed in / or if not the socket is "disconnected" for them not for others.
};
easyrtc.events.on("authenticate", onAuthenticate);
Tested and works perfectly. More testing will follow.

How to import socket.io on client side - SOCKET.IO + NODE.JS

I have been trying to create an online game but when I try to use socket.on(...); or socket.emit(...) it comes up with an error like what is socket. I have seen some posts similar to this one and tried all the solutions but none worked. I have already got io.connect(...); working and it works (I assume this means I have properly set up socket.io-client). I just don't see what I am doing wrong. If you need the code you can simply request it though I don't think it was necessary. Thanks.
To use SocketIO on the client-side, first import it via
import * as io from 'socket.io-client';
Then, probably in a constructor, establish a connection to the server's ip and port running the SocketIO server
const socket = io(`172.16.1.3:81`);
Also in the constructor you will likely want to setup a function to be called when the server sends a certain message type:
socket.on("update-player", handlePlayerUpdateFunction);
and
function handlePlayerUpdateFunction(message) {
console.log(`Received message from server: ${message}`);
}
If this client does not receive the message sent from your server, then something is wrong with your server not being set up correctly to listen on the port.
After trying some things and doing some research I found the solution to my problem. Adding in var socket = io.connect(x.x.x.x:3000); my code started functioning and everything was perfect I had already imported socket.io-client trough CDNJS link on the installation guide. I just had to Initialise the variable.

Communication between an express node server and its displaying html

Really fast, this question may have already been asked, but I am not totally clear on the terminology and have had no success when searching for a solution.
I am attempting to create a simple web application that can receive get and post requests. Then, I would like to take the information I receive from these requests and use them in a javascript file embedded in html that is displayed. I think it may be more clear with code. This is my app.js:
var express = require('express');
var app = express();
var assert = require('assert');
app.use(express.static('javascript'));
app.get('/', function(req, res) {
res.render('index.jade');
});
app.listen(3000);
I would then like to be able to take information received from a get or post request, specifically in JSON format, and then be able to use it in javascript that I have linked to index.jade. To make matters slightly more confusing in index.jade the only line is:
include map.html
So ideally I would be able to get the information to javascript in that html file.
I want to be able to pretty continuously update map.html using javascript based on frequent get and post commands.
This could be a very simple solution, I am pretty new with web application programming in general, and I have been struggling with this problem. Thanks in advance, and ask if you need any clarification.
I think you need to understand what you are doing. You are creating a web server using node.js. Express framework simplifies that for you. The official documentation of express is pretty great. You should refer that especially this link.
Now, in your application, you need to create endpoints for GET and POST requests. You have already created one endpoint "/" (root location) that loads your home page which is the contents of the file index.jade. A small example is :
app.get('/json', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));
});
Jade is a templating engine which resolves to HTML. You should refer its documentation as well. Since as you said, you are not very familiar with these, you could simply use HTML as well.
After this tasks are quite simple. In your javascript, using ajax calls you can access the GET or POST endpoints of your server and do the desired actions.
Hope it helps!
The way I get it you want to be able to call an endpoint (lets assume /awesome) pass some info and then write to a Javascript file that you can then reference in your html.
Something like the below would write a main.js file in your public folder. You can make it write whatever you want.
var fs = require('fs');
fs.writeFile("/public/main.js", "console.log('Hello!')", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
You can then reference /public/main.js in your html.
Check that: Writing files in Node.js
If I misunderstood your intentions, apologies. :)
So you want to reviece continuously data from the server maybe web sockts are an option for you http://socket.io/docs/
This way u will open a stable connection from the client to the server. This is a great way if u want to get updates done by other clients.
If you want to trigger the changes by the client then ajaxs calls(http://www.w3schools.com/ajax/) as hkasera mentioned are the way to go.

Would love some help determining where to start with the Node.JS app file provided with BlueMix

I've been reading tutorials for JS and I've got a good idea of the syntax and methodology, now I'm looking to figure out how to use Node.JS to build an app with BlueMix. I'm pretty fluent with Java, but I'm absolutely new to web programming so I'm pretty lost as to how to start. Forgive my current state of being an absolute beginner, but I'm just really stuck. Here's the file they give you to build off of.
/*eslint-env node*/
//--------------------------------------------------------------------------
// node.js starter application for Bluemix
//--------------------------------------------------------------------------
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
To clarify, I get the general purpose of the code - it's commented pretty well, but I just don't know how to start // test on the BlueMix platform. I tried doing things like adding print statements, but nothing really changes.
To give a little insight on what I'm trying to do: Just create a webpage where a user can input a string and I can post a string in response. I'm just trying to learn BlueMix, so I need to do it on this platform, and in Node JS.
I suggest you to take a look at this tutorial: IBM Bluemix DevOps Services - Develop and deploy a Node.js app. It is useful to get started with DevOps Services (reading your comments it seems that you are using it to deploy from the Web IDE to Bluemix) to get a "Hello World" Node.js Web application on Bluemix. It also shows how to apply some changes and re-push them directly on Bluemix.
Just to answer to your questions, assuming that you have already deployed the starter application (as in your example):
Consider that the starter application uses Express.js, that is an application server framework that helps you to manage the incoming requests. Now let's say that you want to send the string "Hello, World!" in HTTP response when the server receives an HTTP GET request (let's say /printhello). Using express you'll have something like:
app.get('/printhello', function (req, res) {
res.send('Hello, World!');
});
Now you just need to do the HTTP GET /printhello from a web page (for example the index page under the public folder of the starter application). You could for example use an onclick event to send the request to the server. You will see that the server receives it and sends the response to the browser, that will show the string "Hello, World!".
The reason why you can't see the "starting server" log is that console.log prints in the Node.js console, not into the HTTP response, so you can't see that from the client. To see that output you can use cf logs (please refer to this blog post).
Finally, I invite you to take a look at the Bluemix - Node.js SDK documentation, it is really simple and clear.
I hope this can give you some starting points.
Check out https://github.com/IBM-Bluemix/bluemix-hello-node. It provides a pretty good starting place for node. There are somethings you need to code around for Node to work for Bluemix. The biggest is binding to the correct port, the port is given through process.env.PORT. I have pasted a super simple Node.app below (the rest of the code is at the GitHub link above).
var express = require("express"),
app = express();
var port = process.env.PORT || 8080;
app.use(express.static(__dirname + '/public'));
app.get("/hello", function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"})
response.end("Hello World!\n");
});
app.listen(port);

socket.io-client object is not a function

I opened a question here earlier (Socket.io trigger events between two node.js apps?), this was much help, but I am confused out of my mind.
I keep getting object is not a function on my client side script.
A little setup, I have a front end site that is served with express localhost:9200 then I have a back end app localhost:3100 that is also served with express and I am trying to emit events from localhost:9200 to the socket.io server localhost:3100
Client script for website localhost:9200
// I have tried many different ways
var socket = io('http://localhost:3100');
var socket = io('http://localhost');
var socket = io();
EDIT
The issue was with the above of course, because io in the above case for some reason was an object when it should be a function, I came across an old post which mentioned using var socket = io.connect('http://localhost:3100'); connect and that worked, I though it was depreciated or something, I have no clue why the docs don't mention this but it fixed my issue.
All result in object is not a function. I include the client side script like this
// tried some different ways
<script src="http://localhost:3100/socket.io/socket.io.js"></script>
<script src="socket.io/socket.io.js"></script> // this is a 404
I have installed https://github.com/automattic/socket.io-client and on the server for the front end website :9200 I have set it up like.
// tried a couple ways to connect
var socket = require('socket.io-client')('http://localhost:3100');
var socket = require('socket.io-client')('http://localhost');
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});
I am confused on how to properly configure this so that I can get my site to emit socket events to my server and visa versa?
Well I figured it out, this is pretty ridiculous but on the client side javascript I needed to add var socket = io.connect('http://localhost:3100'); the io.connect made it work versus var socket = io('http://localhost:3100');
Maybe I missed it but the docs don't say to use io.connect https://github.com/automattic/socket.io-client whatever it works and I am happy, any thoughts on why the docs don't mention this would be great.
The difference is io.connect is pre 1.0 syntax. They changed it for whatever reason. These are the exact kind of fun surprises I have come to expect in socket.io.

Categories

Resources