I have a node WebServer capable of communicating with Browser(say browserInstance) and linux terminal(say ProxyInstance) via Websockets. The job of the webserver is to handover the data from terminal to WebBrowser and vice-verse. Please find the server.js code below:
var express = require('express');
var expressWs = require('express-ws');
var expressWs = expressWs(express());
var app = expressWs.app;
var appForpage = express();
var browserInstance;
var ProxyInstance;
var browserCounter = 0;
var ProxyCounter = 0;
app.ws('/fromBrowser', function(ws, req, next) {
console.log("~~~~~~~~~~~~BROWSER");
if(browserCounter == 1){
ws.on('message', function(msg) {
console.log("Messagae from Browser :", msg);
ProxyInstance.send(msg);
});
}else{
browserInstance = ws;
ws.on('message', function(msg) {
console.log("Message from Browser :", msg);
ProxyInstance.send(msg);
});
browserCounter = 1;
}
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
app.ws('/fromProxy', function(ws, req, next) {
console.log("~~~~~~~~~~~~PROXY");
if(ProxyCounter == 0){
ProxyInstance = ws;
ProxyCounter = 1;
}else if(browserCounter == 1){
ws.on('message', function(msg) {
console.log("Message from Proxy: ", msg);
browserInstance.send(msg);
});
}
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
appForpage.use(express.static(__dirname + '/public/')); // index.html resides in public directory
appForpage.listen(5000)
app.listen(3000)
First I am creating ws connection from proxy to webserver(/fromProxy) and then from browser(/fromBrowser). The connection was successfully created. When i try to send data from Browser to proxy via Webserver, it works fine. In return to the 1st message at proxy end when tries to communicate Browser via WebServer, this one failed. I haven't received any message from Proxy. I need to run the respective ends in the same order(Proxy first and then Browser..).
I am just beginner to node. I haven't find any example over internet for my case. What am I missing here ?
That's really silly :( .I haven't registered my messsage callback from proxy. Please find the working code below.
var express = require('express');
var expressWs = require('express-ws');
var expressWs = expressWs(express());
var app = expressWs.app;
var appForpage = express();
var browserInstance;
var ProxyInstance;
var browserCounter = 0;
var ProxyCounter = 0;
app.ws('/fromBrowser', function(ws, req, next) {
console.log("~~~~~~~~~~~~BROWSER");
if(browserCounter == 1){
ws.on('message', function(msg) {
console.log("Messagae from Browser :", msg);
ProxyInstance.send(msg);
});
}else{
browserInstance = ws;
ws.on('message', function(msg) {
console.log("Message from Browser :", msg);
ProxyInstance.send(msg);
});
browserCounter = 1;
}
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
app.ws('/fromProxy', function(ws, req, next) {
console.log("~~~~~~~~~~~~PROXY");
if(ProxyCounter == 0){
ProxyInstance = ws;
ProxyCounter = 1;
}
/*This is the place where i went wrong. damnn..*/
ws.on('message', function(msg) {
console.log("Message from Proxy: ", msg);
browserInstance.send(msg);
});
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
appForpage.use(express.static(__dirname + '/public/')); // index.html resides in public directory
appForpage.listen(5000)
app.listen(3000)
Related
I have implemented socket.io with node.js http server. The server pushes the Realtime data to the clients. I noticed a problem that when the server is restarted the client does not get data automatically means it does not reconnect automatically with the server. Please suggest the solution. My client code is as below
client index.html
<script>
var socket = io.connect('http://localhost');
socket.on('field', function (data) {
console.log(data); });
</script>
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8070);
var mysocket = 0;
function handler(req, res)
{
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log('index.html connected');
mysocket = socket;
});
//udp server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("msg: " + msg);
if (mysocket != 0){
mysocket.emit('field', "" + msg);
}
});
server.on("listening", function () {
var address = server.address();
console.log("udp server listening " + address.address + ":" +
address.port);
});
server.bind(41181);
I've implemented a websockets api on top of a swagger-express node server.
For websockets I'm using express-ws which utilises the excellent ws library.
However I have come across a problem where the function setInterval is not being called when a websocket client connects.
Confusingly though in the ws.on('connection' function the console.log('websocket connected'); does execute while the setInterval function does not.
Can someone please point out what is wrong with my code?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var expressWs = require('express-ws')(app);
var IndexWS = require('./api/controllers/indexWS');
var config = {
appRoot: __dirname // required config
};
app.ws('/', function(ws, req) {
ws.on('connection', function(conn) {
console.log('websocket connected');
setInterval(function timeout() {
console.log('conn');
}, 500);
});
ws.on('close', function() {
console.log('The connection was closed!');
});
ws.on('error', function() {
console.log('websocket error!');
});
ws.on('message', function(msg) {
setTimeout(function timeout() {
ws.send("500 delay");
}, 500);
});
console.log('websocket connected');
});
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 3030;
app.listen(port, '0.0.0.0');
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('server running on port ' + port );
}
});
I have an express backend which includes:
var express = require("express");
var app = express();
var expressWs = require('express-ws')(app);
and:
app.get(/test/, function(req, res){
res.send('{"hello" : "world" }');
});
app.ws('/', function(ws, req) {
ws.on('message', function(msg){
var data = JSON.parse(msg);
if(data.action == "login"){
console.log("logged in!")
}
});
});
I want to be able to close the websocket without closing the app. How do I do this?
ws.close() is what you are looking for
Here it is :
app.get(/test/, function(req, res) {
res.send('{"hello" : "world" }');
});
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
var data = JSON.parse(msg);
if(data.action == "login"){
console.log("logged in!")
}
});
ws.on('close', function(msg) {
console.log('connection closed...');
});
});
I have a issue with socket.io with rooms.
See the server code:
This code below is working properly.
io.on('connection', function(socket){
socket.join("myroom");
socket.on('chat message', function(data){
io.in("myroom").emit('chat message', data);
});
});
But I want the user to enter the room after an event.
Like the code below.
io.on('connection', function(socket){
socket.on('chat message', function(data){
io.in("myroom").emit('chat message', data);
});
socket.on('join', function(name, device, room){
socket.join("myroom");
});
});
It's almost the same code , but does not work. What am I doing wrong?
The event is being called correctly.
Edit. Added the front-end code:
var socket = io.connect('http://localhost:5000');
$('#msg_form').submit(function(){
socket.emit('chat message', $("#m").val(), "myroom");
$('#m').val('');
return false;
});
$("#user").submit(function() {
var name = $("#name").val();
var room = $("#room").val();
var device = navigator.userAgent;
if (name === "" || name.length < 2) {
$("#errors").empty();
$("#errors").append("Please enter a name");
$("#errors").show();
} else {
socket.emit("join", name, device, room);
$("#messages").focus();
}
});
Thank you.
I made this small demo to explain, I simulate the client-side event by setTimeout functions:
Server side:
var http = require('http');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(9999);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.on('message', function(data){
io.in("myroom").emit('message', data);
});
socket.on('join', function(name, device, room){
console.log("new client has joining a room");
socket.join("myroom");
});
});
Client Side:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:9999');
setTimeout(function () { console.log("msg emmited to server");
socket.emit('join');
},
10000);
setTimeout(function () {
console.log("msg emmited to server");
socket.emit("message","message from client");
},
20000);
socket.on("message",function(data){
console.log("message received from server ="+data);
}
);
</script>
In your $("#user").submit(...) handler, you do not prevent the default action of the form so it is likely that the page is reloaded right after you hit the submit button. And, this will reset your connection right after you hit join, giving you a newly initialize connection that is not joined into the room.
You can either add return false; to that handler or add the e argument to the handler and call e.preventDefault() to prevent the page from reloading when you hit submit.
$("#user").submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var room = $("#room").val();
var device = navigator.userAgent;
if (name === "" || name.length < 2) {
$("#errors").empty();
$("#errors").append("Please enter a name");
$("#errors").show();
} else {
socket.emit("join", name);
$("#messages").focus();
}
});
I'm trying to create a dummy socket for use in some of my tests
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.write("hello!");
Getting this error
Error: This socket is closed.
I've also tried creating the socket with
var s = new net.Socket({allowHalfOpen: true});
What am I doing wrong?
For reference, the complete test looks like this
it("should say hello on connect", function(done) {
var socket = new net.Socket();
var client = Client.createClient({socket: socket});
socket.on("data", function(data){
assert.equal("hello", data);
done();
});
client.connect();
// writes "hello" to the socket
});
I don't think the server is put into listening state. This what I use..
// server
require('net').createServer(function (socket) {
console.log("connected");
socket.on('data', function (data) {
console.log(data.toString());
});
})
.listen(8080);
// client
var s = require('net').Socket();
s.connect(8080);
s.write('Hello');
s.end();
Client only..
var s = require('net').Socket();
s.connect(80, 'google.com');
s.write('GET http://www.google.com/ HTTP/1.1\n\n');
s.on('data', function(d){
console.log(d.toString());
});
s.end();
Try this.
The production code app.js:
var net = require("net");
function createSocket(socket){
var s = socket || new net.Socket();
s.write("hello!");
}
exports.createSocket = createSocket;
The test code: test.js: (Mocha)
var sinon = require('sinon'),
assert = require('assert'),
net = require('net'),
prod_code=require('./app.js')
describe('Example Stubbing net.Socket', function () {
it("should say hello on connect", function (done) {
var socket = new net.Socket();
var stub = sinon.stub(socket, 'write', function (data, encoding, cb) {
console.log(data);
assert.equal("hello!", data);
done();
});
stub.on = socket.on;
prod_code.createSocket(socket);
});
});
We can create socket server using net npm module and listen from anywhere. after creating socket server we can check using telnet(client socket) to interact server.
server.js
'use strict';
const net = require('net');
const MongoClient= require('mongodb').MongoClient;
const PORT = 5000;
const ADDRESS = '127.0.0.1';
const url = 'mongodb://localhost:27017/gprs';
let server = net.createServer(onClientConnected);
server.listen(PORT, ADDRESS);
function onClientConnected(socket) {
console.log(`New client: ${socket.remoteAddress}:${socket.remotePort}`);
socket.destroy();
}
console.log(`Server started at: ${ADDRESS}:${PORT}`);
function onClientConnected(socket) {
let clientName = `${socket.remoteAddress}:${socket.remotePort}`;
console.log(`${clientName} connected.`);
socket.on('data', (data) => {
let m = data.toString().replace(/[\n\r]*$/, '');
var d = {msg:{info:m}};
insertData(d);
console.log(`${clientName} said: ${m}`);
socket.write(`We got your message (${m}). Thanks!\n`);
});
socket.on('end', () => {
console.log(`${clientName} disconnected.`);
});
}
function insertData(data){
console.log(data,'data');
MongoClient.connect(url, function(err, db){
console.log(data);
db.collection('gprs').save(data.msg , (err,result)=>{
if(err){
console.log("not inserted");
}else {
console.log("inserted");
}
});
});
}
using telnet:
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hi
We got your message (hi). Thanks!
you need to connect your socket before you can write to it:
var PORT = 41443;
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.connect(PORT, function(){
s.write("hello!");
});
It will useful code for websocket
'use strict';
const express = require('express');
const { Server } = require('ws');
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = process.env.PORT || 5555;
const INDEX = '/public/index.html';
const router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
router.get('/', function(req, res) {
res.sendFile(INDEX, { root: __dirname });
});
const server = express()
.use(router)
.use(bodyParser.json())
.use(cors)
.listen(PORT, () => {
console.log(`Listening on ${PORT}`)
});
const wss = new Server({ server });
wss.on('connection', (ws) => {
ws.on('message', message => {
var current = new Date();
console.log('Received '+ current.toLocaleString()+': '+ message);
wss.clients.forEach(function(client) {
client.send(message);
var getData = JSON.parse(message);
var newclip = getData.clipboard;
var newuser = getData.user;
console.log("User ID : "+ newuser);
console.log("\nUser clip : "+ newclip);
});
});
});