I am trying to get nodejs client-server with tcp working. This is my code:
server.js containing the code for server
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
console.log("Started Server");
server.listen(1337, '127.0.0.1');
client.js containing the code for client
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
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');
});
when I run in 2 separate terminals node server.js , node client.js I get this error:
Started Server
events.js:154
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at exports._errnoException (util.js:856:11)
at TCP.onread (net.js:546:26)
Process finished with exit code 1
But if i Combine both of the codes together in a single process it works fine. Anyone have any idea what the problem can be?
Related
I wanna make an tcp server with nodejs . When i start the server in the terminal it says nothing, and when i start the client the client gets the message but in the server terminal, it prints:
events.js:292
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on Socket instance at:
at Socket.onerror (internal/streams/readable.js:760:14)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -54,
code: 'ECONNRESET',
syscall: 'read'
}
When i start the client again, the server is still running, i needed to stop the server using killall node.
How can i fix this error.
Server:
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Connected to server !\r\n');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
Client:
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
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');
});
I have a TCP/IP device that I have written script in python to connect and receive data from and this works. I am now trying to do something similar with nodejs but keep running in to either connection errors or security issues with the buffer depending on the nodejs methods I have tried.
This is the python script that works;
import socket
import csv
import datetime
from decimal import Decimal
import time
UDP_IP = "10.0.0.122"
UDP_PORT = 1025
MESSAGE = "#01\r"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(encoding='utf-8'), (UDP_IP, UDP_PORT))
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print ("received message:", str(data))
Here are 3 methods I have tried with varying errors listed in comments in js. I am new to node js and could really do with some help.
Thanks in advance
// //Method 1
// var net = require('net');
// var client = new net.Socket();
// client.connect(1025, '10.0.0.122', function() {
// console.log('Connected');
// client.write('Hello, server! Love, Client.');
// });
// 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');
// });
//Method 2
// // Include Nodejs' net module.
// const Net = require('net');
// // The port number and hostname of the server.
// const port = 1025;
// const host = '10.0.0.122';
// // Create a new TCP client.
// const client = new Net.Socket();
// // Send a connection request to the server.
// client.connect({ port: port, host: host }), function() {
// // If there is no error, the server has accepted the request and created a new
// // socket dedicated to us.
// console.log('TCP connection established with the server.');
// // The client can now send data to the server by writing to its socket.
// client.write('#01\r');
// };
// // The client can also receive data from the server by reading from its socket.
// client.on('data', function(chunk) {
// console.log(`Data received from the server: ${chunk.toString()}.`);
// // Request an end to the connection after the data has been received.
// client.end();
// });
// client.on('end', function() {
// console.log('Requested an end to the TCP connection');
// });
//Method 1 and 2 give this error
// events.js:287
// throw er; // Unhandled 'error' event
// ^
// Error: connect ECONNREFUSED 10.0.0.122:1025
/ / at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
// Emitted 'error' event on Socket instance at:
// at emitErrorNT (internal/streams/destroy.js:92:8)
// at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
// at processTicksAndRejections (internal/process/task_queues.js:84:21) {
// errno: 'ECONNREFUSED',
// code: 'ECONNREFUSED',
// syscall: 'connect',
// address: '10.0.0.122',
// port: 1025
// }
//Method 3
var PORT = 1025;
var HOST = '10.0.0.122';
var dgram = require('dgram');
var message = new Buffer('#01\r');
var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
if (err) throw err;
console.log('UDP message sent to ' + HOST +':'+ PORT);
client.close();
});
//Method 3 error
// [Running] node "c:\Users\admin\Nodejs tcp test\app.js"
// (node:6032) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability
issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
// UDP message sent to 10.0.0.122:1025
// [Done] exited with code=0 in 0.155 seconds
I have figured it with a little help from google. There are some good examples for a UDP connection in js.
With a pointer in the right direction from Rodrigoms github project,
https://github.com/rodrigoms2004/ServerSocketTCP_UDP
I managed to achieve the same as I was getting in my python file using the following code.
const udp = require('dgram')
// creating a client socket
const client = udp.createSocket('udp4')
//buffer msg
const data = Buffer.from('#01\r')
client.on('message', (msg, info) => {
console.log('Data received from server : ' + msg.toString())
console.log('Received %d bytes from %s:%d\n', msg.length, info.address, info.port)
})
//sending msg
client.send(data, 1025, '10.0.0.122', error => {
if (error) {
console.log(error)
client.close()
} else {
console.log('Data sent !!!')
}
})
setTimeout( () => {
client.close()
},1000)
I tried to build a chat box server by node.js. When the browser requestes the page, it workes well at first. But when I refresh the page, the Server crashes.
Below is the error message:
events.js:183
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at _errnoException (util.js:1022:11)
at TCP.onread (net.js:615:25)
I used the node --inspect index.js, but could not find the point.
Below is the code of index.js:
const http = require('http');
const fs = require('fs');
const extract = require('./extract');
const wss = require('./websockets-server');
var handleError = function (err,res) {
res.writeHead(404);
res.end();
}
var server = http.createServer(function (req, res) {
console.log("Responding to a request.");
var filePath = extract(req.url);
console.log("filePath:"+filePath);
fs.readFile(filePath,function (err,data) {
if(err){
handleError(err,res);
return;
}else {
res.end(data);
}
})
})
server.listen(3000);
When I comment the 4th line, the import of websockets-server. Server works well when I refresh the page. Maybe it's about the websocket while it works without websocket.
Below is code of websockets-server.js:
const WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var port = 3001;
var ws = new WebSocketServer({
port:port
});
var message = [];
console.log('websockets server started');
ws.on('connection', function (socket) {
console.log('client connection established');
message.forEach(function (msg) {
socket.send(msg);
})
socket.on('message', function (data) {
console.log('message received: ' + data);
message.push(data);
ws.clients.forEach(function (clientSocket) {
clientSocket.send(data);
});
});
});
Does the problem is about the websocket? Whether should I do process when the client shutdown the connection with the server while refreshing the page.
extract.js below:
const path = require('path');
var extractFilePath = function (url) {
var filePath;
var fileName = 'index.html';
if(url.length > 1){
fileName = url.substring(1);
}
console.log('The fileName is: ' + fileName);
filePath = path.resolve(__dirname, 'app', fileName);
return filePath;
}
module.exports = extractFilePath;
I guess that you maybe execute var ws = new WebSocket("ws://localhost:3001"); in html file. I haven't figured out exact reason about your error as I'm not proficient in WebSocket. But there is a solution:
window.onbeforeunload = function () {
ws.close();
}
close connection before reload, then the error will not reappear.
You need to add an error listener on the socket. Error listener only on the websocket instance does not help in this case.
socket.on('error', function(e){
console.log(e);
});
The ECONNRESET error means that the other side (browser) closed the connection abruptly. On browser refresh, browser simple killed the connection with the websocket server.
To solve this, you have to listen for the error event on the websocket server instance.
// listen for "error" event so that the whole app doesn't crash
wss.on("error", function(error){
console.log(error);
}
I was having the same problem, but it resolved after this command:
npm install #ionic/app-scripts#nightly --save-dev
I started a project with the generator Angular-Fullstack. I want that external Node Clients (running in other machines) can connect to socket server in the Angular-FullStack project.
I have tested it with a simple node server and client and it works fine. The code is:
NODE SERVER:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 9000;
server.listen(port, function(){
console.log('Express server listening on %d port', port);
});
// __dirname is the directory where this file is placed
app.get('/', function (req, res) {
res.sendFile(__dirname + '/browserSocketAppClient.html');
});
io.on('connection', function (socket) {
console.log( 'THE SOCKET: ' + socket.toString());
socket.emit('NODE SOCKET SERVER', { SERVER: 'NODE SOCKET SERVER' });
socket.on('NODE SOCKET CLIENT', function (data) {
console.log(data);
});
});
NODE CLIENT:
var io = require('socket.io-client');
var socket = io.connect('http://192.168.0.101:9000');
socket.on('connect', function() {
console.log( 'NODE SOCKET CLIENT has connected with the server');
});
socket.on('NODE SOCKET SERVER', function (data) {
console.log(data);
socket.emit('NODE SOCKET CLIENT', { CLIENT: 'NODE SOCKET CLIENT' });
});
THE SERVER CONSOLE:
D:\003_IOT\CODE_EXAMPLES\TestSocketIO>node nodeSocketServer
Express server listening on 9000 port
{ CLIENT: 'NODE SOCKET CLIENT' }
THE CLIENT CONSOLE
D:\003_IOT\CODE_EXAMPLES\TestSocketIO>node nodeSocketClient
NODE SOCKET CLIENT has connected with the server
{ SERVER: 'NODE SOCKET SERVER' }
But when I want to use the same NODE CLIENT: with the Angular-Fullstack project, it doesn't work.
I have added this code to myproject/server/config/socketio.js
socketio.js
function onConnect(socket) {
socket.emit('NODE SOCKET SERVER', { SERVER: 'You are connected with NODE SOCKET SERVER' });
socket.on('NODE SOCKET CLIENT', function (data) {
console.log(data);
});
............................
}
And I get in the console of the server this recursive message,
Express server listening on NaN : 9000 in development mode
finished populating users
GET /socket.io/?EIO=3&transport=polling&t=1438187488692-7 200 27ms
[undefined:undefined] SOCKET CONNECTED
GET /socket.io/?EIO=3&transport=polling&t=1438187489437-306 200 9ms
GET /socket.io/?EIO=3&transport=polling&t=1438187493792-8 200 8ms
GET /socket.io/?EIO=3&transport=polling&t=1438187495438-307 200 5ms
GET /socket.io/?EIO=3&transport=polling&t=1438187498815-9 200 4ms
GET /socket.io/?EIO=3&transport=polling&t=1438187501438-308 200 5ms
GET /socket.io/?EIO=3&transport=polling&t=1438187503827-10 200 7ms
But it never really connects.
It has to be something in the configuration in the server side of the Angular-Fullstack project, but I can't fid it.
Any Idea Thanks
I'm looking at this page: http://nodejs.org/api/net.html#net_net_createconnection_options_connectionlistener
Running the code from the page:
var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' listener
console.log('client connected');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});
and I'm getting the error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
shell returned 8
version stuff:
~ % node --version
v0.10.25
~ % uname -a
Linux human1 3.13.0-031300-generic #201401192235 SMP Mon Jan 20 03:36:48 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
I've tried a lot of different ports and I'm positive node isn't already running
Is the net server you're trying to connect to running?
I tried this and it works for me:
net.js
var net = require('net');
var server = net.createServer(function(client) {
console.log('connected');
});
server.listen(8124);
var client = net.connect({port: 8124}, function() {
console.log('client connected');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});
Run:
$ node net.js
connected
client connected