How to make the websocket server be at a router? - javascript

I'm writing a websocket server using nodejs-ws module, but the server can only be at the root of the server, so how I can make it at a child router like localhost:3000/chat?
I need your help, thanks a lot!

Working example:
var ws = require('ws');
var http = require('http');
var httpServer = http.createServer();
httpServer.listen(3000, 'localhost');
var ws1 = new ws.Server({server:httpServer, path:"/chat"});
ws1.on('connection', function(){
console.log("connection on /chat");
});
var ws2 = new ws.Server({server:httpServer, path:"/notifications"});
ws2.on('connection', function(){
console.log("connection on /notifications");
});

could you please tell me how to use this in express?
To route websockets with Express I'd rather use express-ws-routes
var express = require('express');
var app = require('express-ws-routes')();
app.websocket('/myurl', function(info, cb, next) {
console.log(
'ws req from %s using origin %s',
info.req.originalUrl || info.req.url,
info.origin
);
cb(function(socket) {
socket.send('connected!');
});
});

Related

Get all connected peer(Peer.js)

How can i get all connected peers if i have simple server:
var port = 9000;
var express = require('express');
var app = express();
var ExpressPeerServer = require('peer').ExpressPeerServer;
app.get('/', function(req,res){
res.send('server OK');
//console.log(ip.address());
});
var server = require('http').createServer(app);
app.use('/peerjs',ExpressPeerServer(server));
server.listen(port,'0.0.0.0');
and client:
var peer = new Peer(
{host:"hostname",
port:9000,path:"/peerjs",
debug:3,
config:servers,
});
i use peerjs lib. Thank in advance!
Peer.js has method listAllPeersĀ  on the client side. And you can use it if you add allow_discovery: true parameter in options on the server side.
This should help you

Node-HTTP-Proxy error

I am trying to implement a node http proxy for the first time with my simple twitter tweeter. I have never used this before and tried following the docs (https://github.com/nodejitsu/node-http-proxy) with no luck. Can anyone point me in the right direction? Also, is it okay to run this locally on a mac? Thanks
var express = require('express');
var app = express();
var port = 8300;
var twitter = require('twitter');
var twit = new twitter({ keys and stuff })
var http = require('http'),
httpProxy = require('http-proxy');
twit.post('statuses/update', {status: "Hello world!"}
//this works
httpProxy.createProxyServer({target:'http://localhost:3000'}).listen(3000);
// Create your target server--- WHat exactly does this mean??
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(3000);
You should not use this lib for proxing you request. This lib is for make your own proxy server. Look at example how to use proxy with twitter lib

socket.io connection not heppening

This is first time, I am using socket.io.I stuck at initial stage itself.sorry it's may be simple question.
server side code :
Inside my server.js I written the following code.
var express = require('express')
,io=require('socket.io')
,http = require('http')
var app = express();
server = http.createServer(app);
io = io.listen(server,{ log: false });
Now I trying to make connection inside server.js file,like in the following way.
io.sockets.on('connection', function (socket) {
console.log("This is testing");
io.to(socket.id).emit('notification', 'for your eyes only');
});
client side code :
var socket = io.connect("http://localhost");
socket.on('connect', function () {
console.log("connect")
});
socket.on('notification', function (data) {
console.log(data);
});
I open application in browser, as per my code it suppose to console connect statement but it's not happening.
my server is running on port no :80Where am I did wrong, can anyone help me.
Thanks.
Here is the working code for me in express it may help you.
var express = require('express')
, app = express()
, server = require('http').Server(app)
, io = require('socket.io')(server)
var defaultPort = 6001 ;
server.listen(defaultPort, function() {
console.log('Server Started');
});
io.sockets.once('connection', function(socket) {
return io.sockets.emit('new-data', {
channel: 'stdout',
value: "Your Data Goes Here"
});
socket.on('disconnect', function(){
});
});
On Client Side
<script>
$(function() {
var socket = io.connect('http://localhost'); //if you are trying on server put server url if you are working on local then use localhost
socket.on('new-data', function(data) {
$('#YouDivid').html(data.value);
});
});
</script>

socket.io reconnect socket.socket.connect doesn't work

sorry for posting this issue again, but most of the posts related don't answer my question.
i'm having issues to use multiple connections with the socket.io
i don't get the "socket.socket.connect" method to work, yet i get feedbacks from the first connection.
Here's my structure:
var iosocket = null;
var firstconnection = true;
var ip = "http://xxx.xxx.xxx"
var ipPort = 8081
function callSocket() {
iosocket = null;
iosocket = io.connect(ip,{port:ipPort,rememberTransport:true, timeout:1500});
if (firstconnection) {
firstconnection= false;
iosocket = io.connect(ip,{port:ipPort,rememberTransport:true, timeout:1500});
iosocket.on('connect', function () {console.log("hello socket");});
iosocket.on('message', function(message) {});//end of message io.socket
iosocket.on('disconnect', function () {console.log("disconnected");});
} else {
if (iosocket.connected === true) {
console.log("heyhey still connected");
iosocket.disconnect();
}
iosocket.socket.connect(ip,{port:ipPort,rememberTransport:true,timeout:1500});
}
};
it simply doesn't get any feedback from the second connection
i simply solved that IE8 bug by adding
<!DOCTYPE html>
at the top of the html
I think I know why this isn't working. For server-side code, this doesn't seem correct for socket.io. The connect method is used for clients and not servers. I think you are trying to make the server listen on a port. In that case, you should do:
var socket = require('socket.io');
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
io.on('connection', function (client) {
client.on('someEvent', function(someVariables){
//Do something with someVariables when the client emits 'someEvent'
io.emit('anEventToClients', someData);
});
client.on('anotherEvent', function(someMoreVariables){
//Do more things with someMoreVariables when the client emits 'anotherEvent'
io.emit('anotherEventToClients', someMoreData);
});
});
server.listen(8000);

Socket.io 400 (Bad Request)

I have this piece of code on my server
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
io.sockets.on('connection', function (socket) {
console.log("Socket connected");
});
I just want to create a connection
and on the client -
<script src="public/javascripts/socket.io.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3000');
</script>
And when I open my browser I get this error in console:
GET http://127.0.0.1:3000/socket.io/1/?t=1404410309733 400 (Bad Request) socket.io.js:1659
XHR finished loading: GET "http://127.0.0.1:3000/socket.io/1/?t=1404410309733".
I've already done this like 10 times and I never get this. Does anyone know how to fix it?
I think an older version of socket-io could be the reason.
I was getting this problem when I was using 0.9.16 version. I upgraded to following and it worked.
<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>

Categories

Resources