以下是net tcp客户端代码
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello server');
});
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');
});
client.write(' Hello server')写在client.connect范围内。 有没有办法在client.connect范围之外使用它。
我尝试了以下代码但未能向服务器发送任何内容。但是,client.write的返回值返回true。
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
});
client.write('Hello server'); //Did not work