I want to realize a simple client-server connection using Nodejs. But I've encountered with the following problem.
Consider the code
server.js:
var net = require('net'),
sys = require('sys');
net.createServer(onConnection).listen(8124);
function onConnection(socket) {
socket.setNoDelay(true);
socket.addListener("connect", function () {
sys.puts('client connected: ' + this.remoteAddress);
});
socket.addListener("data", function (data) {
sys.puts("message: \n" + data + "\n - end of msg.");
});
socket.addListener("end", function () {
sys.puts('end of connection');
this.end();
});
}
sys.puts('Server running at 127.0.0.1:8124');
client.js:
var net = require('net'),
sys = require('sys');
var stream = net.createConnection(8124);
stream.addListener("connect", function(){
sys.puts('connected');
stream.write('a');
stream.flush();
stream.write('b');
stream.flush();
});
stream.addListener("data", function(data){
sys.puts("Message: \n" + data + "\n - end of msg.");
});
When I run client.js I sometimes get only one message 'ab' instead of two messages 'a' and 'b'.
Is there some 'right method' to deal with that?
Nodejs is very good to streaming audio and video, but nodejs is a new technology, so it's don't have a lot of softwares yet.
What are Streams? Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, there are four types of streams − Readable − Stream which is used for read operation. Writable − Stream which is used for write operation.
In the copy function, you created an input or readable stream using fs. createReadStream() . You also generated a new name for the destination, output a copy of the file, and created an output or writable stream using fs. createWriteStream() .
“The front-end engineers were having to write a lot of Java code to produce the website, but they also had to write a lot of JavaScript on the client side. With Node, they can do all their work in JavaScript.” said Kim Trott, director of user interface engineering at Netflix.
TCP is a stream protocol. Single write
on one end of the pipe can result in multiple "reads" on the other end, and the other way around. You have to either explicitly tell the other side how many bytes you are sending by including the length in the message; or provide easily recognizable message delimiters. In any case you need to read in a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With