Node - ENONET when connecting to a socket - node.js

Executing this code:
var fs = require('fs');
var Socket = require('net').Socket;
var socket = new Socket();
console.log('connecting to: ' + server.host + ':' + server.port );
socket.connect( server.host, server.port );
socket.on('error', function(err) {
console.log(arguments);
});
socket.on('connect', function() {
console.log('connected');
});
socket.on('end', function() {
console.log('socket ended');
});
Always throws this error:
{ '0': { [Error: connect ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'connect' } }
I'm on CloudLinux(x64) based shared hosting with SSH access.

You have your host and port backwards. According to the documentation, you should be doing:
socket.connect(server.port, server.host);

Server Side:-
var net = require('net');
var server = net.createServer(functi`on (socket){
socket.write("hi\n");
socket.write("you there\n");
socket.on("data", function(dd) {
console.log(data);
});
});
server.listen(8001);
Client side:-
var fs = require('fs');
var Sock = require('net');
var socket = Sock.Socket();
socket.connect(8001,"127.0.0.1", function() {
console.log('connecting to: ' + server.host + ':' + server.port );
});
socket.on('connect', function() {
console.log('connected');
});
socket.on('error', function(err) {
console.log(arguments);
});
socket.on('end', function() {
console.log('socket ended');
});

Related

connecting refused for web socket socket.io

I am loading my scripts using
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="/js/chat.js"></script>
My chat.js script is :
var socket = io();
socket.on('connect', function(){
var chatForm = document.forms.chatForm;
if (chatForm) {
var chatUsername = document.querySelector('#chat-username');
var chatMessage = document.querySelector('#chat-message');
chatForm.addEventListener("submit", function(e){
console.log("working")
//prevents page from reloading
e.preventDefault();
//emit the message with the socket
socket.emit('postMessage',{
username: chatUsername.value,
message: chatMessage.value,
});
chatMessage.value='';
chatMessage.focus();
});//chatform event
socket.on('updateMessages', function(data) {
showMessage(data);
});//update messages
}//chatForm
})
function showMessage(data) {
var chatDisplay = document.querySelector('.chat-display')
var newMessage = document.createElement('p');
newMessage.className = 'bg-success chat-text';
newMessage.innerHTML = '<strong>' + data.username + '<strong>:</strong>' +
data.message
chatDisplay.insertBefore(newMessage, chatDisplay.firstChild);
}
My app.js file uses:
app.set('port', process.env.PORT || 3000 );
var server = app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
io.attach(server);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
I am getting the following errors in my console and have no idea how to fix them. Somebody please help!
The server is listening on port 3000. My console is saying that there is an unhandled 'error' event
In your app.js file, you should connect socketIO before listening:
const socketIO = require('socket-io');
const io = socketIO(app);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
app.set('port', process.env.PORT || 3000 );
app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
Let try it, because I think after listening, everything won't work. We should connect socketIO before listening.

Nodejs , Redis,Sockets

I have a nodejs app which reads data from redis and I am unable to push it into socket. In the c.write(message) part, if I hardcode(example c.write('hello') ,the messages are being put to the socket but when i put it as c.write(message), nothing is going to the socket. Thanks in advance,
var net = require('net');
var split = require('split');
var Redis = require('ioredis');
var redis = new Redis();
var server = net.createServer(function(c) {
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
redis.subscribe('test-channel');
redis.on('message', function(channel, message) {
console.log(message);
c.write(message);
c.pipe(c);
});
});
server.on('error', (err) => {
throw err;
});
server.listen(3005, 'localhost', () => {
console.log('server bound');
});
I have got the answer.
Just add below lines to your code :
var message_redis = message+'\r'+'\n';
c.write(message_redis);

Can't create socket server from http module

I wanna create socket server like a Socket.io because socket.io can't work with Corona SDK. So I need custom socket server. I create socket server with using net module and it is work good. But I need using http module because I write REST API. I try create sample socket server from http module but have errors.
var net = require('net');
var HOST = 'localhost';
var PORT = 9999;
var server = require('http').createServer(function(request, response) {
response.end('Hello from server');
});
server.on('connection', function(socket) {
socket.on('data', function(data) {
data = data.toString('utf-8');
console.log(data);
socket.write('Hello from server');
});
socket.on('error', function(error) {
console.log(error);
});
});
server.listen(PORT, HOST);
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
If I run this script I got error:
CONNECTED TO: localhost:9999
I am Chuck Norris!
Error: This socket is closed
at Socket._writeGeneric (net.js:692:19)
at Socket._write (net.js:743:8)
at doWrite (_stream_writable.js:329:12)
at writeOrBuffer (_stream_writable.js:315:5)
at Socket.Writable.write (_stream_writable.js:241:11)
at Socket.write (net.js:670:40)
at Socket.<anonymous> (/var/work/projects/edorium/Server/test/test.js:49:16)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
{ Error: Parse Error
at socketOnData (_http_server.js:411:20)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at Socket.Readable.push (_stream_readable.js:136:10)
at TCP.onread (net.js:560:20) bytesParsed: 0, code: 'HPE_INVALID_METHOD' }
Connection closed
Why this happed and how fix this?
Additional to answer
I add HTTP headers to request and all works good!
Code sample below:
var http = require('http');
var net = require('net');
var express = require('express');
var HOST = 'localhost';
var PORT = 9999;
var app = express();
var server = http.Server(app);
app.get('/', function (req, res) {
res.send('Hello World!fff');
});
server.listen(PORT, HOST);
server.on('connection', function(socket) {
socket.on('data', function(data) {
data = data.toString('utf-8');
console.log(data);
socket.write('Hello from server');
});
socket.on('error', function(error) {
console.log(error);
});
socket.on('end', function() {
console.log('Socket end');
});
});
// Client
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
var messagae = '' +
'GET /' +
'Host:localhost:9999' +
'Content-Type:text/plain;charset=windows-1251' +
'Content-Length:6' +
'Connection:Keep-Alive;' +
'Hello!';
client.write(messagae);
});
client.on('data', function(data) {
console.log('DATA: ' + data);
});
client.on('close', function() {
console.log('Connection closed');
});
at TCP.onread (net.js:560:20) bytesParsed: 0, code: 'HPE_INVALID_METHOD' }
Since you have explicitly created a HTTP server this server is expecting a HTTP request. But you are just sending "I am Chuck Norris!" which is definitely not a HTTP request. Therefore the server closes the connection.
To send a HTTP request you might use http.request. Alternatively you can study the HTTP standard and build a proper HTTP request yourself.
Your client was disconnect
var net = require('net');
var HOST = 'localhost';
var PORT = 9999;
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.on('data', function(data){
console.log(data);
textChunk = data.toString('utf8');
console.log(textChunk);
socket.write("================");
});
});
server.listen(PORT, '127.0.0.1');
server.listen(PORT, HOST);
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
var i = 0;
client.on('data', function(data) {
console.log('Received: ' + data);
i++;
if(i==2)
client.destroy();
} );
client.on('close', function() {
console.log('Connection closed');
});

SOLVE NodeJS Socket.io server not receive message

I start create server with Nodejs and socket.io in simple way.
In client connect just fine but when emit pong to server it never show.
This code:
SERVER
var PORT = 3003;
var io = require('socket.io')(PORT);
var clients = [];
setInterval (function() {
io.sockets.emit('ping');
}, 3000);
io.on('connection', (function(socket) {
socket.emit ('welcome', { message: 'Connection complete', id: socket.id });
clients.push ({id: socket.id, clientSocket: socket});
print ('Client connected ' + socket.id);
socket.on('disconnect', function() {
clients.splice(clients.indexOf(socket), 1);
print (socket.id + " is disconnected.");
});
socket.on('pong', function(args) {
print (args + " is pong.");
});
}).bind(this));
print('Server starting ...');
CLIENT:
var PORT = 3003;
var io = require('socket.io-client');
var socket = io.connect('http://localhost:' + PORT);
socket.on('connect', function(){
print ('Client connected...');
});
socket.on('welcome', function(args) {
print (args.message + ' / ' + args.id);
// socket.disconnect();
});
socket.on ('ping', function(args) {
socket.emit ('pong', { id: socket.id });
print ('Receive ping...');
});
print ('Client Starting...');

How to create a simple socket in node.js?

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);
});
});
});

Resources