I have created communication between client and server using socket.io, Now I am sending commands from client to server using WebSockets, I would like to run these received commands from the client on the server
Here is my solution
HTML (client)
<html>
<body>
I am client
</body>
<script>
const ws = new WebSocket('ws://localhost:9898/');
ws.onopen = function() {
console.log('WebSocket Client Connected');
ws.send('npm run build');
};
ws.onmessage = function(e) {
console.log("Received: '" + e.data + "'");
};
</script>
</html>
Here is server.js
const http = require('http');
const WebSocketServer = require('websocket').server;
const server = http.createServer();
server.listen(9898);
const wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
const connection = request.accept(null, request.origin);
connection.on('message', function(message) {
console.log(message.utf8Data);
connection.sendUTF('Hi this is WebSocket server!');
});
connection.on('close', function(reasonCode, description) {
console.log('Client has disconnected.');
});
});
Now when we run the server and open index.html, the server receives the following message
`npm run build`
Now how do I run this command on a server using a child process?
You can use child_process to spawn a new process for your server.js like below
const http = require('http');
const WebSocketServer = require('websocket').server;
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const server = http.createServer();
server.listen(9898);
const wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
const connection = request.accept(null, request.origin);
connection.on('message', function(message) {
console.log(message.utf8Data);
const { stdout, stderr } = await exec(message.utf8Data);
console.log('stdout:', stdout);
console.log('stderr:', stderr);
connection.sendUTF('Hi this is WebSocket server!');
});
connection.on('close', function(reasonCode, description) {
console.log('Client has disconnected.');
});
});
Related
I am using Node.JS and I am using http to use an express server which then my WebSocket is on, but when I try to connect to the socket it gives me an 'Expected HTTP/' error.
My code:
const express = require('express');
const app = express();
const server = require('http').createServer(app);
app.get('/', (req, res) => {
res.send("Hello World!");
});
const wss = new WebSocket.Server({ server });
// web socket stuff here
server.listen(port, () => {
console.log(`HTTP Server started on port ${port}`);
});
And then on another Node project, I have this to connect:
const WebSocket = require('ws');
const ws = new WebSocket.WebSocket('ws://localhost:3000/ws');
Any help?
//my memory in this question was that
const WebSocket = require('ws');
const socket = new WebSocket.Server({ port: 2424, host: "localhost"});
socket.on('connection', function(ws, wss) {
var domain = wss.headers.origin;
//etc...
But maybe you have a front for communicate if is not the good response ?
I have 2 scripts in node js. One uses 'http' and other uses 'net'. I want to make these scripts together in one script. My 'http' script are as below:
const http = require('http');
const hostname = 'localhost';
const port = 3000;
const server = http.createServer((req, res) => {
console.log(req.headers);
res.statusCode = 200;
res.end('<html><body><h1>Hello, World!</h1></body></html>');
})
server.listen(port, hostname);
'net' script:
var net = require('net');
var client = new net.Socket();
client.connect(4352, 'x.x.x.x', function() {
console.log('Connected');
client.write('%1POWR 1\r\n');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
My purpose is to run the 'net' script once I start the 'http' script.
Wrap the whole net script in a exported function:
var net = require('net');
module.exports = () => {
var client = new net.Socket();
client.connect(4352, 'x.x.x.x', function() {
console.log('Connected');
client.write('%1POWR 1\r\n');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
}
Import and execute the exported function in http script:
const http = require('http');
const hostname = 'localhost';
const port = 3000;
require('path/to/net/script')() //Add to anywhere you like
const server = http.createServer((req, res) => {
console.log(req.headers);
res.statusCode = 200;
res.end('<html><body><h1>Hello, World!</h1></body></html>');
})
server.listen(port, hostname);
So, I have this app called server and the other one called client, server providers all the data for the client to consume. The thing is, when i try to emit from server (port 8080) and receive to client (port 80) nothing happens
server: app.js
var app = require ("./config/server.js");
var http = require('http').createServer(app);
var io = require("socket.io")(http);
http.listen(8080, function(){
console.log('Server side instagram_clone_v01 online');
});
io.sockets.on('connect', function (socket) {
console.log("conectou socket.id="+socket.id);
});
When the server database insert new photo, this is called:
io.emit("newPhoto");
client: app.js
var app = require('./config/server');
app.listen(80, function(){
console.log('Server client instagram_clone_v01 online');
});
var io = require('socket.io');
This is called inside a ejs code:
const socket = io.connect('http://localhost:8080', {transports: ['websocket', 'polling', 'flashsocket']});
socket.on('newPhoto',function(){
load_posts();
});
Edited with the Answer of Federico
I added io.origins('*:*'); to server, but emit isn't emitting
I don't know why you are using io.sockets.on, I couldn't find it in the documentation. I've tried to clean the code, give it a try.
server.js
var app = require ("./config/server.js");
var http = require('http').Server(app);
var io = require("socket.io")(http);
http.listen(8080, function(){
console.log('Server side instagram_clone_v01 online');
});
io.on('connect', socket => {
console.log("user" + socket.request.user.id + "connected");
socket.on('disconnect', function() {
console.log('A user has disconnected');
}
io.emit("newPhoto");
});
client.js
//io() works only when connecting to a socket hosted on the same url/server
// For connecting to an external socket hosted elsewhere, you would use io.connect('URL');
var socket = io();
socket.on('newPhoto',function(){
load_posts();
});
In the page where your user being redirected after login, you should include these scripts:
<script src="/socket.io/socket.io.js"></script>
<script src="/client.js"></script>
I am working with socket.io , so i created server on app.js and connect socket to client and i see emit('message') is printing to the client console, Now i want to send another message from different file consumer.js and emit message to client but its throwing exception on server side io.on is not a function. Any idea what is implemented wrong in consumer.js file ?
app.js
var express = require('express');
var app = express();
var consumer = require('./consumer');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + "/public"));
io.on('connection', function(client) {
console.log('Client connected...');
client.emit('message', ' hello from server');
});
server.listen(3000, function () {
console.log('Example app listening on port 3000!');
consumer.start();
});
consumer.js
var io = require('socket.io');
function startConsumer(consumer) {
consumer.on('message', function (message) {
logger.log('info', message.value);
io.on('connection', function(client) {
console.log('Consumer connected...');
client.emit('Consumer-Message', 'Message from dit consumer');
});
});
consumer.on('error', function (err) {
console.log('error', err);
});
};
exports.start = start;
angularCtrl.js
socket.on('message',function (data) {
console.log(data);
});
socket.on('Consumer-Message',function (data) {
console.log(data);
});
On client side, I have this code:
var serverAddress = "http://localhost:8081";
var socket = io(serverAddress);
socket.on('connect', function(){
console.log("Connected to server on %s", serverAddress);
});
socket.emit("xxx", {text : "attack"});
And on server, I have this one:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var socket = require('socket.io').listen(server);
socket.on('connect', function() {
console.log('A user is connected to server');
});
socket.on('xxx', function(data) {
console.log(data);
});
connect event is fired and caught on server, but xxx event isn't even fired nor caught. What's wrong? Console.log didn't report any error.
You're confusing the socket.io server with a socket.io connection.
The server receives a connection event when a new client connection is made. The argument for that event (usually called socket) represents that connection. This is the object that you need to use to listen to messages:
// server
...
var io = require('socket.io').listen(server);
...
io.on('connection', function(socket) {
console.log('A user is connected to server');
socket.on('xxx', function(data) {
console.log(data);
});
});