How do I send a message to my socket.io websocket from the command line in linux?
You can write a simple client like this (let's name it client
with no extension):
#!/usr/bin/env node
const socket = require('socket.io-client')('http://localhost:3000');
const someDelay = 10;
socket.on('connect', function () {
console.log('connected...');
if (process.argv[2] && process.argv[3]) {
console.log('sending ' + process.argv[2] + ': ' + process.argv[3]);
socket.emit(process.argv[2], process.argv[3]);
setTimeout(() => {
process.exit(0);
}, someDelay);
} else {
console.log('usage: ./client.js <event> <data>');
process.exit(1);
}
});
with a very basic package.json
{
"name": "client",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "client"
},
"dependencies": {
"socket.io-client": "^1.4.6"
}
}
Then run npm install
, give client
permissions to be executed and you can run it with (for example) ./client message testControl
What do you think? ;)
You can use iocat cli client from npm which is based on Socket.IO.
$ iocat --socketio ws://127.0.0.1:8081
< Hello there
For a more low-level (socket.io-independent) solution you can use my tool websocat.
Example session for communicating with socket.io's chat example:
$ websocat 'wss://socket-io-chat.now.sh/socket.io/?transport=websocket'
< 0{"sid":"yGVElkNCXVgc5w_JOVtc","upgrades":[],"pingInterval":25000,"pingTimeout":60000}
< 40
> 2
< 3
> 42["add user", "websocat"]
< 42["login",{"numUsers":15}]
> 42["new message", "Hello from websocat"]
< 42["typing",{"username":"1223"}]
< 42["new message",{"username":"1223","message":"Reply from browser."}]
< 42["stop typing",{"username":"1223"}]
> 42["new message", "OK, may flood again."]
>
denotes messages to be typed.
I was able to work around this by doing the following:
Create a new endpoint in your server
app.post('/sendSocketMessage', function(req, res){ console.log("Request is "+JSON.stringify(req.body)); socketManager.parse(req.body); //send message directly to your socket parser res.status(200).send("OK"); });
Send data using curl
curl --noproxy localhost, -X POST --data "data=testControl,loadModels,start," http://localhost:8081/sendSocketMessage