Client:
var iosocket = io.connect();
iosocket.on('connect', function () {
iosocket.on('message', function(message) {
console.log(message)
});
});
$('#input').keypress(function(event) {
if(event.which == 13) {
event.preventDefault();
iosocket.send($('#input').val());
}
});
server: (ingnore require part)
var socket = require('socket.io');
conn = function (socket) {
console.log("connnect");
socket.on('disconnect', function (socket) {
console.log("disconnect");
});
socket.on('message', function (data) {
var socket1 = new net.Socket();
socket1.connect (PORT, HOST, function() {
socket1.write(data);
socket1.end();
});
socket1.on('data', function(data) {
socket.broadcast.emit('message', data);
socket.emit('message',data);
});
socket1.on('error', function(exception){
console.log('Exception:');
console.log(exception);
});
socket1.on('drain', function() {
console.log("socket1 drain!");
});
socket1.on('timeout', function() {
console.log("socket1 timeout!");
});
socket1.on('close', function() {
console.log('Socket1 closed');
});
});
}
var io = socket.listen(server, { log: false });
io.sockets.on('connection', conn );
Problem1(solved but needs feedback): The response (mkessage variable) I was getting in client was in hex array format, I tried setencoding and tostring method but it did not solve the problem. The following code converted the hex array in readable string.
byte = '';
for (var i=0; i < data.length; i++) {
byte += String.fromCharCode( parseInt(data[i], 16).toString(16) );
}
Problem 2 :
The tcp socket socket1 is created for every time and it is taking huge time to do this. how do I create and use socket1 so that it don't get closed after every write?
Does the status of other guy listening at PORT HOST force it to close?
Have you tried to explicitly set encoding of your socket?
socket.on('message', function (msg) {
var socket1 = new net.Socket();
socket1.setEncoding('utf8'); //< explicitly request utf8
socket1.connect (PORT, HOST, function() {
socket1.write(msg);
socket1.end();
});
See NodeJS documentation for more details.
If this does not help, could you share the code of TCP server listening at HOST:PORT (see socket1 initialization)?
Edit
As mentioned in the comment(s) below: unless you call setEncoding() on your socket, 'data' callback receives Buffer object. You should convert it to String for the broadcast.
socket1.on('data', function(data) {
socket.broadcast.emit('message', data.toString());
});