Example #1
0
var net = require('net');
var cw = 1024
var ch = 768
var squareSize = 10



var client = new net.Socket();
client.connect(1234, '100.123.2.16', function() {
  console.log('Connected');
  setInterval(function(){
    var px = parseInt(Math.random()*cw)
    var py = parseInt(Math.random()*ch)
    for (var i=0; i<= squareSize; i++){
      for (var k=0; k<= squareSize; k++){
        var command = 'PX ' + Math.round(px+i) + ' ' + Math.round(py+k) + ' 000000\n';
        client.write(command);
      }
    }

  }, 10)
});

client.on('data', function(data) {
  console.log('Received: ' + data);
  client.destroy(); // kill client after server's response
});

client.on('error', function(err) {
   console.log(err)
client.connect(1345, '127.0.0.1', function () {
	console.log('connected');
	client.write('Hello server!');
});
 .then(function (resp) {
   console.log(resp)
   socket.end()
 }).catch(function () {
Example #4
0
var net = require('net');
require('./uuid.js'); // Adds Math.uuid()

var jsonDelimiter = '_-^emil^-_';
var client = new net.Socket();
client.setNoDelay(true);
client.setKeepAlive(true, 0);

var player;

/**
 * Connects to the poker server.
 *
 * @param host
 * @param port
 * @param botPlayer - The player implementation
 */
function connect(host, port, botPlayer) {

	var saveForNext = null;
	
    player = botPlayer;

    client.connect(port, host, function () {
        console.log('CONNECTED TO: ' + host + ':' + port);
    });

    // Add a 'data' event handler for the client socket
    // data is what the server sent to this socket
    client.on('data', function (data) {
Example #5
0
		sock.on('data', function(buffer) {
			console.log(buffer.toString());
			//process.exit();
			sock.destroy();
		});
Example #6
0
    proxySocket.on('data', function (data) {
        switch (state) {
        case UNAUTHENTICATED:
            /**
             * Parse request
             * Authenticate user
             * Connect to VM
             * Hopefully change state to VMREADY
             */
            try {
                var request = proto.readRequest(data),
                    username = request.authentication.un,
                    password = request.authentication.pw;
                    // secureid = request.authenticate.secureid;
                
                var cred = {userid: username, password: password, secureid: ""};
                
                authenticate(cred, function (err, vm) {
                    if (vm) {
                        proto.writeResponse({"type": "AUTHOK", "message": ""}, proxySocket);
                        
                        /**
                         * Failed connection will be caught in vmSocket.on('error')
                         */
                        vmSocket.connect(config.vm_port, vm.ip, function () {
                            state = VMREADY;
                            proto.writeResponse({"type": "VMREADY", "message": ""}, proxySocket);
                        });

                    } else {
                        proto.writeResponse({"type": "ERROR", "message": err}, proxySocket);
                    }
                });
            } catch (e) {
                proto.writeResponse({"type": "ERROR", "message": "Parser: Bad formed message"}, proxySocket);
            }
            break;
        case VMREADY:
            /**
             * Parse request
             * Send Video Information
             * Change state to PROXYREADY
             */
            try {
                 var request = proto.readRequest(data);
                 if( request.type === 'VIDEO_PARAMS') {
                    // send json VIDEO_INFO
                    proto.writeResponse({"type": "VIDSTREAMINFO", "videoInfo": videoResponseObj}, proxySocket);
                    state = PROXYREADY;
                 }
            } catch (e) {
                 proto.writeResponse({"type": "ERROR", "message": "Parser: Bad formed message"}, proxySocket);    
            }
            break;
        case PROXYREADY:
            /**
             * Proxy data straight through
             */
            vmSocket.write(data);
            break;
        }
    });
client.connect(6000, '127.0.0.1', function() {
  client.write('this message is from node');
});
Example #8
0
 client || (function() {
   client = new net.Socket();
   client.connect(port, host); 
 })();
Example #9
0
client.on('data', function (data) {
    var bp = new baseMessage();
    bp.extractFrom(data);
    if (!bp.getIsExtracted()) {
		console.log('%% nije extraktovan paket.');
	}
	else {
		bp.unpackAsEncryptedMessage(aes128Key);

		// parsing authorization communication?
		if(!authorized) {
			//console.log('RX:', bp.getBinaryPackage().toString('hex'));

			if(authPhase == 1) {
				// parse it
				var chall = new Buffer(16);
				bp.getData().copy(chall, 0);

				// send response to his challenge, which is just 16 random bytes followed by "chall" we got from Server
				var resp = new Buffer(32);

				// stupid random number generator for challenge value
				for(var i=0; i<4; i++) {
					var nr = Math.floor((Math.random() * 0xFFFFFFFF) + 1);
					resp.writeUInt32LE(nr, i*4);
				}

				chall.copy(resp, 16, 0);

				var msg = new baseMessage();
				msg.setIsSync(true); // Tell server to re-sync, we have nothing pending for him (in this example)
				msg.setData(resp);
				var aaa = msg.buildEncryptedMessage(aes128Key, crypto.randomBytes(16));
				client.write(aaa, 'hex');

				console.log('< Sent auth request - Phase 2');

				// now if socket doesn't get disconnected after a few seconds, we will get another message with NO data.
				// we should only see if there is SYNC set in Header so that we re-sync!

				authPhase++;
			}
			else if(authPhase == 2) {
				console.log('Authorized!');

				authorized = true;

				if(bp.getIsSync()) {
					TXserver = 0;
				}

                // start a simulator that will send some stuff to Clients
                tmrSimulator = setInterval(simulator, 5000);
			}
		}
		// not authentication communication
		else {
			if (bp.getIsAck()) {
				console.log('> Got ACK, header:', bp.getHeader(), 'TXsender:', bp.getTXsender());
			}
			else {
				console.log('> Got DATA, header:', bp.getHeader(), 'TXsender:', bp.getTXsender());

				// acknowledge immediatelly (but only if this is not a notification)
				var bpAck = new baseMessage();
				bpAck.setIsAck(true);
				bpAck.setTXsender(bp.getTXsender());

				// not a notification? ACKnowledge
				if(!bp.getIsNotification()) {
					if (bp.getTXsender() <= TXserver) {
						bpAck.setIsProcessed(false);
						console.log('  ...Warning: re-transmitted command, not processed!');
					}
					else if (bp.getTXsender() > (TXserver + 1)) {
						// SYNC PROBLEM! Client sent higher than we expected! This means we missed some previous Message!
						// This part should be handled on Clients side.
						// Client should flush all data (NOT A VERY SMART IDEA) and re-connect. Re-sync should naturally occur
						// then in auth procedure as there would be nothing pending in queue to send to Server.

						bpAck.setIsOutOfSync(true);
						bpAck.setIsProcessed(false);
						console.log('  ...Error: Server sent out-of-sync data! Expected:', (TXserver + 1), 'but I got:', bp.getTXsender());
					}
					else {
						bpAck.setIsProcessed(true);
						TXserver++; // next package we will receive should be +1 of current value, so lets ++
					}

                    client.write(bpAck.buildEncryptedMessage(aes128Key, crypto.randomBytes(16)), 'hex');
					console.log('  ...ACK sent back for TXsender:', bp.getTXsender());
				}
				else {
					bpAck.setIsProcessed(true); // we need this for bellow code to execute
					console.log('  ...didn\'t ACK because this was a notification.');
				}

				if (bpAck.getIsProcessed()) {
					// system messages from Server?
					if (bp.getIsSystemMessage()) {
						console.log('  ...system message received!');

						// lets see what we got here, it can be a server-stored-variable or timestamp.
						console.log(bp.getData()); // too lazy, just print it to console
					}
					else {
						console.log('  ...fresh data!');
						console.log(bp.getData());

						// do something with data we received from Server!
					} // not system message
				} // processed
			}
		} // not authentication communication
    }

    // Close the client socket completely
    //client.destroy();
});
Example #10
0
module.exports.sendData = function(data) {
	socket.write(JSON.stringify(data));
};
Example #11
0
 socket.on('tcp', function(message) {
         tcpClient.write(message+"\r\n"); 
         return;
 });
Example #12
0
socket.on('data',(evt)=>{
    console.log(String(evt));
    //socket.end("bye");
    socket.destroy();
});
Example #13
0
/**
 * Created by KICT-02 on 2016-07-19.
 */
/**
 * Created by KICT-02 on 2016-07-19.
 */

const net = require('net');


const ip = '192.168.0.21';
const PORT = 8080;

let socket = new net.Socket();

socket.connect(PORT,ip,()=>{
    console.log("connect to :" + ip + PORT);
    let req = {
        name : '김진희',
        value : 94
    }
    socket.write(JSON.stringify(req));

});

socket.on('data',(evt)=>{
    console.log(String(evt));
    //socket.end("bye");
    socket.destroy();
});
socket.on('error',(evt)=>{
Example #14
0
client.on('data', function(data) {
  console.log('Received: ' + data);
  client.destroy(); // kill client after server's response
});
Example #15
0
 vmSocket.on('timeout', function () {
     vmSocket.end();
 });
Example #16
0
                        setTimeout(function () {

                            socket1.end();
                            socket2.end();
                        }, 10);
Example #17
0
exports.proxyConnection = function proxyConnection(proxySocket) {
    var vmSocket = new net.Socket(),
        
        // initial state
        state = UNAUTHENTICATED,
        videoResponseObj = videoResponse();

    proxySocket.on('data', function (data) {
        switch (state) {
        case UNAUTHENTICATED:
            /**
             * Parse request
             * Authenticate user
             * Connect to VM
             * Hopefully change state to VMREADY
             */
            try {
                var request = proto.readRequest(data),
                    username = request.authentication.un,
                    password = request.authentication.pw;
                    // secureid = request.authenticate.secureid;
                
                var cred = {userid: username, password: password, secureid: ""};
                
                authenticate(cred, function (err, vm) {
                    if (vm) {
                        proto.writeResponse({"type": "AUTHOK", "message": ""}, proxySocket);
                        
                        /**
                         * Failed connection will be caught in vmSocket.on('error')
                         */
                        vmSocket.connect(config.vm_port, vm.ip, function () {
                            state = VMREADY;
                            proto.writeResponse({"type": "VMREADY", "message": ""}, proxySocket);
                        });

                    } else {
                        proto.writeResponse({"type": "ERROR", "message": err}, proxySocket);
                    }
                });
            } catch (e) {
                proto.writeResponse({"type": "ERROR", "message": "Parser: Bad formed message"}, proxySocket);
            }
            break;
        case VMREADY:
            /**
             * Parse request
             * Send Video Information
             * Change state to PROXYREADY
             */
            try {
                 var request = proto.readRequest(data);
                 if( request.type === 'VIDEO_PARAMS') {
                    // send json VIDEO_INFO
                    proto.writeResponse({"type": "VIDSTREAMINFO", "videoInfo": videoResponseObj}, proxySocket);
                    state = PROXYREADY;
                 }
            } catch (e) {
                 proto.writeResponse({"type": "ERROR", "message": "Parser: Bad formed message"}, proxySocket);    
            }
            break;
        case PROXYREADY:
            /**
             * Proxy data straight through
             */
            vmSocket.write(data);
            break;
        }
    });

    /**
     * Send data to client
     */
    vmSocket.on('data', function (data) {
        proxySocket.write(data);
    });

    /**
     * Done
     */
    proxySocket.on("close", function (had_error) {
        vmSocket.end();
        proxySocket.destroy();
    });

    /**
     * On Error shut it down
     */
    proxySocket.on("error", function (err) {
        proxySocket.end();
        vmSocket.end();
    });

    /**
     * On VM Socket close - close Client connection
     */
    vmSocket.on('close', function () {
        proto.writeResponse({"type": "ERROR", "message": "VM closed the connection"}, proxySocket);
        proxySocket.end();
    });

    vmSocket.on('timeout', function () {
        vmSocket.end();
    });

    /**
     * Close connection on VM error
     */
    vmSocket.on("error", function (err) {
        // On error connecting to VM the state doesn't change
        console.log("Error connecting to VM: ",err);
        var error = "VM Error: " + err;
        proto.writeResponse({"type": "ERROR", "message": error}, proxySocket);
    });
};
 client.on('connect', common.mustCall(function() {
   client.end();
 }));
var net = require('net');

// this server only receives
var server = net.createServer(function(socket) {
  socket.on('data', function(data) {
    console.log('node server received', data.toString());
  });

  socket.on('close', function() {
    console.log('node server closed');
  });
});

server.listen(6001, '127.0.0.1');

// this client only sends
var client = new net.Socket();

client.connect(6000, '127.0.0.1', function() {
  client.write('this message is from node');
});

client.on('close', function() {
  console.log('node client closed');
});
Example #20
0
export function client({ name, server_name, host, port })
{
	server_name = server_name ? '"' + server_name + '"' : 'TCP server'

	// TCP socket
	const socket = new net.Socket()

	// // `log` global variable doesn't exist yet
	// console.log(`${name ? '[' + name + '] ' : ''}Connecting to ${server_name} at ${host}:${port}`)

	// connect to the log server via TCP
	socket.connect({ host, port })

	// the data will be interpreted as UTF-8 data, and returned as strings
	socket.setEncoding('utf8')

	// constants
	const max_retries = undefined
	const reconnection_delays = [0, 100, 300, 700, 1500]

	// internal state
	// let connection_lost
	let reconnecting
	let retries_made

	// encodes JSON messages to their textual representation
	let message_encoder

	// decodes JSON messages from their textual representation
	let message_decoder

	// resets internal state
	function reset()
	{
		reconnecting = false
		retries_made = 0
		// connection_lost = false
	}

	function connection_lost()
	{
		// stop writing encoded JSON messages to the TCP socket
		if (message_encoder)
		{
			message_encoder.end()
		}
	}

	// When the TCP socket connection is successfully established
	socket.on('connect', function()
	{
		if (reconnecting)
		{
			log.info(`Reconnected to ${server_name}`)
		}
		else
		{
			log.debug(`Connected to ${server_name} at ${host}:${port}`)
		}

		// in case of reconnect
		// if (reconnecting)
		// {
		// }

		// encodes JSON messages to their textual representation
		message_encoder = new Message_encoder()

		// stop write encoded JSON messages to the TCP socket,
		message_encoder.pipe(socket)

		// decodes JSON messages from their textual representation
		message_decoder = new Message_decoder()

		// on JSON message parse error
		message_decoder.on('error', error =>
		{
			// // just drop the message on syntax error
			// console.log(`${name ? '[' + name + '] ' : ''}JSON Message Decoder error`)
			// log.error(error)

			socket.emit('error', error)
		})

		// receive JSON messages on TCP socket	
		socket.pipe(message_decoder)

		// reset internal state
		reset()

		messenger.underlying_connection_established(message_decoder, message_encoder)

		if (reconnecting)
		{
			messenger.reconnected()
		}
		else
		{
			log.debug(`Connected to ${server_name}. Initializing messenger.`)
			messenger.initialize()
		}
	})

	// Emitted when an error occurs on the TCP socket. 
	// The 'close' event will be called directly following this event.
	socket.on('error', function(error)
	{
		if (!reconnecting)
		{
			log.error(`Lost connection to ${server_name}`) // , error)
		}
	})

	// when TCP socket is closed
	socket.on('close', function(had_error)
	{
		connection_lost()

		if (message_decoder)
		{
			socket.unpipe(message_decoder)
			message_decoder.removeAllListeners('error')
		}

		if (message_encoder)
		{
			message_encoder.unpipe(socket)
		}

		messenger.underlying_connection_closed()

		// log this event
		if (had_error)
		{
			log.debug('Connection closed due to an error')
		}
		else
		{
			log.debug('Connection closed')
		}

		// if should not try connecting further
		if (max_retries === 0)
		{
			log.info(`Will not try to reconnect further. Destroying socket.`)

			// indicate messenger shutdown
			return messenger.ended(new Error('Reconnection not allowed'))
		}

		// if was trying to reconnect to the server 
		// prior to receiving the TCP socket 'close' event,
		// then it means that reconnection attempt failed.
		if (reconnecting)
		{
			log.debug(`Reconnect failed`)

			// if max retries count limit reached, should stop trying to reconnect
			if (exists(max_retries) && retries_made === max_retries)
			{
				log.info(`Max retries count reached. Will not try to reconnect further.`)

				// indicate messenger shutdown
				return messenger.ended(new Error('Max reconnection retries count reached'))
			}
		}

		// now in the middle of reconnecting to the server
		reconnecting = true

		const reconnect = () =>
		{
			// if connection established before the reconnection timer fired, then do nothing
			if (!reconnecting)
			{
				return
			}

			log.debug(`Trying to reconnect`)

			retries_made++
			socket.connect({ host, port })
		}

		const reconnection_delay = retries_made < reconnection_delays.length ? reconnection_delays[retries_made] : reconnection_delays.last()

		reconnect.delay_for(reconnection_delay)
	})

	// create a duplex object stream

	// function Message_stream(parameters)
	// {
	// 	stream.Duplex.call(this, merge(parameters, { objectMode: true }))
	// }

	// util.inherits(Message_stream, stream.Duplex)

	// // when a JSON object is written to this stream
	// Message_stream.prototype._write = function(object, encoding, callback)
	// {
	// 	// if the connection to the TCP server is lost
	// 	if (connection_lost)
	// 	{
	// 		// then this message is also lost
	// 		// (may implement caching and retrying in the future)
	// 		return callback(new Error('Message lost due to connection issues'))
	// 	}
	//
	// 	// encode the JSON message into a utf-8 string 
	// 	// and send it down the TCP socket
	// 	message_encoder.write(object, undefined, callback)
	// }
	//
	// Message_stream.prototype._read = function(count)
	// {
	//
	// }

	// // All JSON objects written to the stream 
	// // will be encoded and sent to the TCP server
	// message_stream.pipe(message_encoder)

	// // create the message stream
	// const message_stream = new Message_stream()

	// // return the stream
	// return message_stream

	const messenger = new Messenger({ name })

	return messenger
}
Example #21
0
var net = require('net')

var SERVER_IP_ADDR = '127.0.0.1'
var SERVER_IP_PORT = 8001
var PUSH_IP_PORT = 8231

var HEAD_LEN = 8

var client = new net.Socket();
client.connect(SERVER_IP_PORT, SERVER_IP_ADDR, function() {
	console.log('Connected to : ' + SERVER_IP_ADDR + ':' + SERVER_IP_PORT);
});


//-----------protobufjs: format push message
var ProtoBuf = require("protobufjs");

var builder = ProtoBuf.loadProtoFile("../MessageFormat/message.proto"),
	stock = builder.build("stocksim"),
	Stock = stock.Stock;



//-----------zmq: pub/sub mode
var zmq = require('zmq');
var publisher = zmq.socket("pub");

publisher.bind("tcp://*:" + PUSH_IP_PORT, function(err) {
  if (err) throw err;
});
Example #22
0
module.exports = function(ip, port) {

        var newVideoConnection;
        var newKwmConnection;

        var client = new net.Socket();
        client.connect(port, ip, function() {
                getAllValues();
        });

        var callbacks = {};

        client.on('data', function(data) {
                //console.log(response);
                var response = messages.MattiResponse.decode(data);
                if (callbacks[response.ticket]) {
                        console.log("not undefined");
                        callbacks[response.ticket](response);
                        callbacks[response.ticket] = undefined;
                }
                if (response.videoConnection) {
                        raiseNewVideoConnection(response.videoConnection.cpu, response.videoConnection.con);

                }
                if (response.videoConnections) {
                        console.log("video connections");
                        response.videoConnections.videoConnection.forEach(function(c) {
                                raiseNewVideoConnection(c.cpu, c.con);
                        });
                }
                if (response.kwmConnections) {
                        response.kwmConnections.kwmConnection.forEach(function(c) {
                                raiseNewKwmConnection(c.con, c.cpu);
                        });
                }
        });

        function setVideoConnection(cpu, con, callback) {
                var ticket = createTickect();
                if (ticket > -1) {
                        var message = messages.MattiRequest.encode({
                                ticket,
                                videoConnection: {
                                        cpu,
                                        con
 }
                        });
                        callbacks[ticket] = callback;
                        client.write(message);
                }

        }

        function getAllValues(callback) {
                var i = 1;
                var ticket = createTickect();
                if (ticket > -1) {
                        var message = messages.MattiRequest.encode( {
                                ticket,
                                requestValue: {
                                        values: i
                                }
                        });
                        client.write(message);
                }
        }

        function createTickect() {
                for (var i = 1; i < 10000; i++) {
                        if (callbacks[i] === undefined) {
 return i;
                        }
                }
                return -1;
        }

        function raiseNewVideoConnection(cpu, con) {
                console.log("new connection " + cpu + " " + con);
                if (newVideoConnection) {
                        newVideoConnection(cpu, con);
                }
        }

        function raiseNewKwmConnection(con, cpu) {
                if (newKwmConnection) {
                        newKwmConnection(con, cpu);
                }
        }

        function setNewVideoConnectionCallback(fn) {
                newVideoConnection = fn;
        }

        function setNewKwmConnectionCallback(fn) {
                newKwmConnection = fn;
        }

        return {
                setVideoConnection,
                setNewVideoConnectionCallback,
                setNewKwmConnectionCallback,
                getAllValues
        }
}
Example #23
0
/**
 * Registers the player for a new game in the supplied room.
 *
 * @param room
 */
function playAGame(room) {
    client.write(JSON.stringify(createRegisterForPlayRequest(room)) + jsonDelimiter);
}
Example #24
0
                authenticate(cred, function (err, vm) {
                    if (vm) {
                        proto.writeResponse({"type": "AUTHOK", "message": ""}, proxySocket);
                        
                        /**
                         * Failed connection will be caught in vmSocket.on('error')
                         */
                        vmSocket.connect(config.vm_port, vm.ip, function () {
                            state = VMREADY;
                            proto.writeResponse({"type": "VMREADY", "message": ""}, proxySocket);
                        });

                    } else {
                        proto.writeResponse({"type": "ERROR", "message": err}, proxySocket);
                    }
                });
// Import the net module
var net = require('net');

/*
 * Class: net.Socket
 * This object is an abstraction of a TCP or local socket. net.Socket instances implement a 
 * duplex Stream interface. They can be created by the user and used as a client (with connect()) 
 * or they can be created by Node and passed to the user through the 'connection' event of a server.

 * new net.Socket([options])
 * Construct a new socket object.
*/

var client = new net.Socket();

client.connect(1345, '127.0.0.1', function () {
	console.log('connected');
	client.write('Hello server!');
});

client.on('data', function (data) {
	console.log('Received :' + data);
	
	/* Ensures that no more I/O activity happens on this socket. Only necessary in case of errors 
	 * (parse error or so).
	 */
	client.destroy();
});

client.on('close', function () {
	console.log('Connection closed');
Example #26
0
 proxySocket.on("close", function (had_error) {
     vmSocket.end();
     proxySocket.destroy();
 });
'use strict'

const modbus = require('../..')
const net = require('net')
const socket = new net.Socket()
const options = {
  'host': '192.168.56.101',
  'port': '502'
}
const client = new modbus.client.TCP(socket)

socket.on('connect', function () {
  client.writeSingleRegister(1002, 333)
    .then(function (resp) {
      console.log(resp)
      socket.end()
    }).catch(function () {
      console.error(arguments)
      socket.end()
    })
})

socket.on('error', console.error)
socket.connect(options)
Example #28
0
 proxySocket.on("error", function (err) {
     proxySocket.end();
     vmSocket.end();
 });
 }).catch(function () {
   console.error(arguments)
   socket.end()
 })
Example #30
0
 cutter.on('packet', function (chunk) {
   callback(null, chunk, chunk.length);
   return client.end(' ');
 });