I have two servers one on port 80 which is a normal web server and than one on port 8080 that is a broadcast server that sends a text string with all the updates to show. However the browser gives me a CORS header 'Access-Control-Allow-Origin' missing. And is it any simple way for me to add the header with the net package? The server code looks as following:
Code to create the server:
var net = require('net');
var fs = require('fs');
var buffer = require('buffer');
var serverHost = "0.0.0.0";
var serverPort = 8080;
var splitter = require('./splitter.js');
var server = net.createServer(function(target) {
// Socket errors
target.on('error', function(error) {
console.log('Socket error: ', error.message);
});
target.on('data', function(data){
// TODO: Verify the data
var number = parseInt(data);
if(!isNaN(number)){
// Adds the client to the list
splitter.addClient(target, number);
}
else{
target.write("Match ID is not correctly formatted");
}
});
});
// Listening for any problems with the server
server.on('error', function(error) {
console.log("Error listening to the server!", error.message);
});
server.listen(serverPort, serverHost);
splitter code (Add client and send data):
var gameids = {1337:[]}
function addClient(client, gameID){
if(matchExists(gameID)){
console.log("Client", client.remoteAddress, "begun watching gameID", gameID,"\n");
var id = gameids[gameID].push(client);
}
else{
client.write("A match with the given ID does not exists");
}
}
function sendData(data, gameID){
if(gameids[gameID].length > 0){
for(i = 0; i < gameids[gameID].length;i++){
console.log(gameids[gameID][i]);
if(gameids[gameID][i].writable){
console.log("Sent data");
gameids[gameID][i].write(data);
}
}
}
}
The function send data is called from my main script which just takes the input from another server and then sends that out to all clients watching.
Related
I can not get the module to send the Server Call Data to the client (see line 36) so that the client can then return the sensor data.
I have run out of ideas, have tried lots of things.
Also if I uncomment 'use strict' why is console.log called as an error?
Note : I have included fhe file .jshintrc in the development directory to ensure ES6 is validated.
The code is as follows;
// See https://techbrij.com/node-js-tcp-server-client-promisify
//'use strict';
const ServerComms = { // Server Comms Data
serverIP :"192.168.100.199",
serverPort : 9000
}; // End ClientComms
var ClientComms = { // Client Comms Data
clientIP :"192.168.100.101",
clientPort : 9000
}; // End ClientComms
var ServerCall = { // Server job call to client
clientIP : ClientComms.clientIP, // '192.168.100.101', Same as ClientComms.clientIP
jobID : 1
}; // End ServerCall
const net = require('net');
class MyServer {
constructor() {
this.address = ServerComms.serverIP;
this.port = ServerComms.serverPort;
this.init();
} // End constructor
init() {
let server = this;
let onClientConnected = (socket) => {
console.log(`Sending request job to RSU : ${ServerComms.serverPort} ${ServerComms.serverIP}`);
server.socket.write( ServerCall.clientIP, ServerCall.jobID ); // Send request and data to client so that client can respond with remote sensor data.
let clientName = `${ClientComms.clientIP} : ${ClientComms.clientPort}`;
console.log(`New client is connected: ${clientName}`);
socket.on('data', (clientData) => {
console.log(`${clientName} Says: ${clientData}`);
socket.write(clientData);
socket.write('exit');
});
socket.only('close', () => {
console.log(`Connection from ${clientName} closed`);
});
socket.on('error', (err) => {
console.log(`Connection ${clientName} error: ${err.message}`);
});
}; // End onClientConnect.
//server.connection = net.createServer(onClientConnected);
server.connection = net.createServer( onClientConnected, function(){
console.log(`Server created at: ${ServerComms.serverIP} : ${ServerComms.serverPort}`);
});
server.connection.listen(ServerComms.serverPort, ServerComms.serverIP, function() {
console.log(`Server started at: ${ServerComms.serverIP} : ${ServerComms.serverPort}`);
}); // End server.connection.listen
} // End init
} // End class Server
module.exports = MyServer;
The calling module is as follows;
// To test server, use following code in another file and run it
const Server = require('./ServerCommsV05.js');
new Server();
I have a connection with POS (point of sale) device. I send it information in hex code and the device prints a receipt.
My problem is that the parser (Readline) doesn't work. When I try to use parser.on("data", console.log), it doesn't return anything.
Here is my code:
const SerialPort = require('serialport');// include the library
const WebSocketServer = require('ws').Server;
const SERVER_PORT = 7000; // port number for the webSocket server
const wss = new WebSocketServer({port: SERVER_PORT}); // the webSocket server
var connections = new Array; // list of connections to the server
const Readline = SerialPort.parsers.Readline;
wss.on('connection', handleConnection);
const myPort = new SerialPort("COM3", {
baudRate: 115200,
});
myPort.on('open', showPortOpen);
myPort.on('close', showPortClose);
myPort.on('error', showError);
const parser = myPort.pipe(new Readline('\r\n'))
console.log('parser setup');
parser.on('data', function(data) {
console.log('data received: ', data);
});
function handleConnection(client) {
console.log("New Connection"); // you have a new client
connections.push(client); // add this client to the connections array
client.on('message', sendToSerial); // when a client sends a message,
client.on('close', function() { // when a client closes its connection
console.log("connection closed"); // print it out
var position = connections.indexOf(client); // get the client's position in the array
connections.splice(position, 1); // and delete it from the array
});
}
function sendToSerial(data) {
console.log("sending to serial: " + data);
myPort.write(data, 'hex');
}
// This function broadcasts messages to all webSocket clients
function broadcast(data) {
console.log(data);
for (myConnection in connections) { // iterate over the array of connections
connections[myConnection].send(JSON.stringify(data)); // send the data to each connection
}
}
function showPortOpen() {
console.log('port open. Data rate: ' + myPort.baudRate);
}
function readSerialData(data) {
// if there are webSocket connections, send the serial data
// to all of them:
if (connections.length > 0) {
broadcast(data);
}
}
function showPortClose() {
console.log('port closed.');
}
function showError(error) {
console.log('Serial port error: ' + error);
}
I receive messages, but they are split and I want to send to client whole message. I tried to define the parser and after that to pipe it. I tried to set parser in SerialPort constructor, changed the delimiter, but no result.
I think that my error is something with the parser.
Here you can see that doesn't return console.log
And here is the result if I use
myPort.on('data', function(data) {
console.log('data received: ', data);
});
The idea is to get whole message after every command and send it to the client.
Use the built-in readline api from SerialPort:
const SerialPort = require('serialport');// include the library
const WebSocketServer = require('ws').Server;
const SERVER_PORT = 7000; // port number for the webSocket server
const wss = new WebSocketServer({port: SERVER_PORT}); // the webSocket server
var connections = new Array; // list of connections to the server
const Readline = SerialPort.parsers.Readline;
wss.on('connection', handleConnection);
const myPort = new SerialPort('COM3', {
baudRate: 115200,
parser: SerialPort.parsers.readline('\r\n')
});
myPort.on('open', showPortOpen);
myPort.on('close', showPortClose);
myPort.on('error', showError);
myPort.on('data', data => readSerialData(data.toString());
// ...
function broadcast(data) {
console.log(data);
for (myConnection in connections) {
connections[myConnection].send(JSON.stringify(data));
}
}
// ...
function readSerialData(data) {
// if there are webSocket connections, send the serial data
// to all of them:
if (connections.length > 0) {
broadcast(data);
}
}
// ...
The message is split again. So I want it whole message to decode it by hex code. Did the problem come from parser?
I have a multiplayer game where my server uses nodejs and TCPSocket (net.createServer) to communicate with a client.
I have thousands of clients connecting to the server and many people are complaining that they are constantly being disconnected from the server.
Here is how my server handles the connections now:
Init:
var net = require("net");
server = net.createServer(function(socket) {
socket.setTimeout(15000);
socket.setKeepAlive(true);
socket.myBuffer = "";
socket.msgsQue = [];
socket.on("data", onData);
socket.on("error", onError);
socket.on("end", onClientDisconnect);
socket.on("timeout", onClientDisconnect);
});
server.listen(port);
Sending to client:
var stringData = JSON.stringify({name:event, message:data});
if (!this.socket.msgsQue || typeof this.socket.msgsQue == "undefined")
this.socket.msgsQue = [];
this.socket.msgsQue.unshift(stringData);
var i = this.socket.msgsQue.length;
while(i--) {
if (this.socket.writable) {
var elem = this.socket.msgsQue[i];
this.socket.write(elem+"\0");
this.socket.msgsQue.splice(i, 1);
} else {
//Unable to write at index "i"
break;//will send the rest on the next attempt
}
}
When disconnected
var onClientDisconnect = function() {
this.myBuffer = "";
delete this.myBuffer;
this.msgsQue = [];
delete this.msgsQue;
this.destroy();
}
Receiving from client
var onData = function(data) {
if (!data || !data.toString()) return;
var raw = data.toString();
this.myBuffer += raw;
var d_index = this.myBuffer.indexOf('\0'); // Find the delimiter
// While loop to keep going until no delimiter can be found
var string;
while (d_index > -1) {
// Create string up until the delimiter
string = this.myBuffer.substring(0,d_index);
// Cuts off the processed chunk
this.myBuffer = this.myBuffer.substring(d_index+1);
onMessage(string, this);//handle
// Find the new delimiter
d_index = this.myBuffer.indexOf('\0');
}
}
A problem I notice is that msgsQue becomes huge because the socket is not writable, but disconnect handler is not fired (or hired later..)
Can you give me some advises on how to optimize this ?
I noticed that sometimes I get disconnected, but I can ping the server, so it is definitely a server-related problem. Can it be because of high load on the server itself?
(I do not want to use socket.io because the last year I had many problems with it like memory leaking, freezing the server app, no support, etc..)
AS3 XMLSocket sends data from all clients started, but data recieved only by last client connected.
I have the flash web client, and if you open for example 2 or more tabs with the app, every client will send the data to socket server, but only THE LAST client connected gets all the data. Here is the link http://151.248.124.213/. It has chat alike interface for now and green button is the SEND button. App gets connected when you hit stage with the mouse. App is connected when the message Connected appears in the screen. To test http://151.248.124.213/ just open 2 or more tabs.
Here is the AS3 code:
Security.loadPolicyFile("xmlsocket://151.248.124.213:3843");
var socket:XMLSocket;
stage.addEventListener(MouseEvent.CLICK, doConnect);
function doConnect(evt:Event):void
{
stage.removeEventListener(MouseEvent.CLICK, doConnect);
socket = new XMLSocket("151.248.124.213", 3000);
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
}
function onConnect(evt:Event):void
{
trace("Connected");
output_txt.text = "Connected\n";
socket.removeEventListener(Event.CONNECT, onConnect);
socket.removeEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(DataEvent.DATA, onDataReceived);
socket.addEventListener(Event.CLOSE, onSocketClose);
}
function onSocketClose(evt:Event):void
{
trace("Connection Closed");
socket.removeEventListener(Event.CLOSE, onSocketClose);
socket.removeEventListener(DataEvent.DATA, onDataReceived);
}
function onError(evt:IOErrorEvent):void
{
trace("Connect failed");
socket.removeEventListener(Event.CONNECT, onConnect);
socket.removeEventListener(IOErrorEvent.IO_ERROR, onError);
}
function onDataReceived(evt:DataEvent):void
{
try {
trace( "From Server:", evt.data );
var msg = evt.data;
output_txt.text += msg + "\n";
}
catch (e:Error) {
trace('error');
}
}
send_btn.addEventListener(MouseEvent.CLICK, send_btn_clicked);
function send_btn_clicked(evt:MouseEvent):void
{
var msg = input_txt.text;
socket.send(msg);
input_txt.text = "";
}
And here is the server code:
var express = require('express');
var app = express.createServer();
app.configure(function () {
app.use(express.static(__dirname));
})
app.listen(80);
var net = require('net');
var mySocket;
var server = net.createServer(function(socket) {
mySocket = socket;
mySocket.on("connect", onConnect);
mySocket.on("data", onData);
});
server.listen(3000);
function onConnect()
{
console.log("Connected to Flash");
}
function onData(d)
{
if(d == "exit\0")
{
console.log("exit");
mySocket.end();
server.close();
}
else
{
console.log("From Flash = " + d);
mySocket.write(d, 'utf8');
}
}
You have to create one socket per client on server side.
Each time a new client is connected, create a new socket. look here for an example.
I am trying to add a new URL path (Node.js home page has given an example to do it.) to a piece of complex existing code (shown below). The existing code already has server configuration code but the code looks very different from the "Building a Node.js Web Server" example that is showing in the Node.js home page.
The new URL path is "/lens/v1/ping" that is sent from the browser window.
If that is the URL path received, I am supposed to send a response Status 200 back to the browser.
I am having difficulties to fit this new URL path and its associated code to the existing code (show below) and I am seeking help. Thank you very much.
/**
* Entry point for the RESTFul Service.
*/
var express = require('express')
var config = require('config');
var _ = require('underscore');
var bodyParser = require("vcommons").bodyParser;
// Export config, so that it can be used anywhere
module.exports.config = config;
var Log = require('vcommons').log;
var logger = Log.getLogger('SUBSCRIBE', config.log);
var http = require("http");
var https = require("https");
var fs = require("fs");
var cluster = require("cluster");
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
logger.info('A worker with #' + worker.id);
});
cluster.on('listening', function (worker, address) {
logger.info('A worker is now connected to ' + address.address + ':' + address.port);
});
cluster.on('exit', function (worker, code, signal) {
logger.info('worker ' + worker.process.pid + ' died');
});
} else {
logger.info("Starting Subscription Application");
createApp();
}
// Create Express App
function createApp() {
var app = express();
app.configure(function () {
// enable web server logging; pipe those log messages through winston
var winstonStream = {
write : function (message, encoding) {
logger.trace(message);
}
}; // Log
app.use(bodyParser({}));
app.use(app.router);
if (config.debug) {
app.use(express.errorHandler({
showStack : true,
dumpExceptions : true
}));
}
});
// Include Router
var router = require('../lib/router')();
// Subscribe to changes by certain domain for a person
app.post('/lens/v1/:assigningAuthority/:identifier/*', router.submitRequest);
// Listen
if (!_.isUndefined(config.server) || !_.isUndefined(config.secureServer)) {
if (!_.isUndefined(config.server)) {
http.createServer(app).listen(config.server.port, config.server.host, function () {
logger.info("Subscribe server listening at http://" + config.server.host + ":"
+ config.server.port);
});
}
if (!_.isUndefined(config.secureServer)) {
https.createServer(fixOptions(config.secureServer.options), app).listen
(config.secureServer.port, config.secureServer.host, function () {
logger.info("Subscribe server listening at https://" + config.secureServer.host
+ ":" + config.secureServer.port);
});
}
} else {
logger.error("Configuration must contain a server or secureServer.");
process.exit();
}
}
function fixOptions(configOptions) {
var options = {};
if (!_.isUndefined(configOptions.key) && _.isString(configOptions.key)) {
options.key = fs.readFileSync(configOptions.key);
}
if (!_.isUndefined(configOptions.cert) && _.isString(configOptions.cert)) {
options.cert = fs.readFileSync(configOptions.cert);
}
if (!_.isUndefined(configOptions.pfx) && _.isString(configOptions.pfx)) {
options.pfx = fs.readFileSync(configOptions.pfx);
}
return options;
}
// Default exception handler
process.on('uncaughtException', function (err) {
logger.error('Caught exception: ' + err);
process.exit()
});
// Ctrl-C Shutdown
process.on('SIGINT', function () {
logger.info("Shutting down from SIGINT (Crtl-C)")
process.exit()
})
// Default exception handler
process.on('exit', function (err) {
logger.info('Exiting.. Error:', err);
});
A browser window executes a HTTP GET request. After the // Include Router call, that is where you would define your express GET function.
...
// Include Router
var router = require('../lib/router')();
//*********
//define your method here, as shown, or in your router file.
app.get('lens/v1/ping', function(req, res){
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end();
} );
//*********
// Subscribe to changes by certain domain for a person
app.post('/lens/v1/:assigningAuthority/:identifier/*', router.submitRequest);
...