How to detect when the socket is opened on client? - javascript

While using socket.io on the client browser side, how can I detect when the socket actually opened? Along with all the other basic default messages (such as errors and disconnection)
I am referring to how the default WebSocket API has websocket.onopen = function(){}, .onerror and .onclose.
Using socket.on("connect", function(){some code here}) and socket.on("connection") does nothing.

you can have a look at:
Docs of SocketIO
because it is such an easy question im adding the message below.
it isnt hard to find the solution to this, just search and you will find what you need.
It is wrong to (be lazy) and ask your question on a platform such as stackoverflow for all you programming information. it is always better to look for docs and examples. because you learn more when you look it up yourself or find it out yourself.
of course you can ask questions when you are really stuck and you cant move forward and you know for sure it takes to long otherwise.
if you want the easy way here is the solution:
http://socket.io/docs/#sending-and-receiving-events
http://socket.io/docs/client-api/
use "disconnect", when disconnect event is triggered on times you dont expect, its is clearly a connection drop.
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');
});
io.on('connection', function(socket){
console.log('a user connected');
});

Ok, so before I tried this
socket.on("connect", function(){
alert("socket open test")
})
and it didn't work but and now I tried again and somehow for some reason it does, sorry for the confusion and waste of time.

Related

What security precautions should one take for a simple .io game with websockets?

I am working on an .io game using node.js and socket.io. Being relatively new to the concept of websockets, I've spent these past few days looking into security measures such as JWT authentication and socket authentication, however, I don't think I fully grasp the purpose of it and whether it is necessary for my game.
In it, the player controls their unit with the WASD keys, so for the most part the client emits information only when the WASD keys are pressed or released. There is no registration and hence no database - users simply type out a name and start playing.
Is this a scenario where I should worry about authentication? Also, I'm considering potential DDOS attacks, such as for example sending an infinite loop that 'presses' and 'releases' the W key. In the server, pressing or releasing it only changes the value of a single variable. However, can firing at sockets rapidly cause the server to crash? If so, what is a surefire way to work around that?
Lastly, look at this example snippet and the questions in the comments:
var path = require('path');
var express = require('express');
var app = express();
var http = require('http');
var server = http.Server(app);
var socketIO = require('socket.io');
var io = socketIO(server);
app.set('port', 1017);
app.use('/files', express.static(__dirname + '/files'));
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname, 'iogame.html'));
});
server.listen(1017, function() {
console.log('Server running on port 1017');
});
io.on('connection', function(socket) {
sendID(socket); //could another user access the data that I send to this particular socket?
socket.on('enterGame', function(data) {
//could this data be emitted by a different user in some way? (could a user 'pretend' to be on another user's socket and emit data?
});
});
If the answer to either question is 'yes', then what is a good approach to avoid such malicious activity? Thank you in advance for any advice.

Detect Websocket close connection when the users close browser?

I am using HTML5 websocket and nodejs in my project to create a simple chat.
Everything works as it should so far.
However, I need to figure out how to detect if the the users that are connected, lost connection somehow and in particular, if they close their browser etc.
I tried the following code.
I can successfully connect like this:
wss.on('connection', function(ws, req) {
//do my stuff here/////
console.log('connection started');
});
However, i cannot see anything in the console when i disconnect by closing the browser.
I use this code to detect connection close:
wss.on('closed', function(ws) {
console.log('connection closed');
});
Could someone please let me know if I am missing something and or doing something wrong?
Thanks in advance.
edit:
This seems to work:
ws.on("close", function() {
console.log("closed");
});
As discussed in this post, the default Websocket implementation doesn't have a way to detect network disconnects, only an intentional disconnect from the user. I recommend that you try to use Socket.IO, as it will do similar what you're looking for, and can detect disconnects. Here's an example:
var io = require('socket.io')(80);
io.on('connection', function (socket) {
socket.on('disconnect', () => {
console.log('User disconnected.')
});
The one disadvantage to using Socket.IO is that you'll have to use a JS library on your client instead of using raw WebSockets, but you'll gain the ability to see when a client disconnects.

Where to put socket.io server in WebStorm Express template

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.

how to close socket server in node-rstp-stream module node js

I am using onvif node js module and node-rstp-stream module to convert RSTP stream to img stream which can be used in phonegap(RSTP stream is not supported in phonegap I think).
Here I am using express js, so whenever I send a request to /livestreaming first time it works fine but not next load it tries to create one instance on same port number which creates an issue. Is there way to check if the server is running close on every request and start it again so that we dont the port already in use error. Is there a way better than this please let me know.
Below is the code which I tried.
app.get('/livestreaming', function (req, res) {
if(cam !== null) {
cam.getStreamUri({protocol:'RTSP'}, function(err, stream) {
newsocket = new Stream({
name: 'mysoc',
streamUrl:stream.uri,
wsPort: 8888
});
});
} else {
res.json({"error":"connect to camera"});
}
});
The node-rtsp-stream library does not provide any way to check if the port is already in use, neither any way to close the socket server.
So, from my point of view you have two options:
Try to connect to your socket server port to use if it is available, for example by doing a ping, and only launch a new Stream in case is not.
Since the node-rtsp-stream library is very simple, and I already have practice with it, you can add this code right after your newly created stream:
newsocket.wsServer.on('error', function() {
newsocket.mpeg1Muxer.stream.kill();
});
So, where this came? If you take a look to the library, you will find that the wsServer is your socket server and mpeg1Muxer is the stream open with your camera. Because of the already in use error, the server won't launch, but you should also kill the ffmpeg process. This way, if the server is already running, nothing happend, and if not, it will launch.
This last solution is little bit tricky, but I thing it will work.
Hope it helps

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