在 node.js 中使用 net.createConnection(port, [host]) 创建一个 tcp 套接字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6346911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating a tcp socket with net.createConnection(port, [host]) in node.js
提问by vitez
Anyone here can give me a few pointers working with sockets in node.js?
这里的任何人都可以给我一些关于在 node.js 中使用套接字的指针吗?
can open a tcp connection say on 172.0.0.1 on port 8000 for example using net.createConnection(port, host)
可以在端口 8000 上的 172.0.0.1 上打开一个 tcp 连接,例如使用 net.createConnection(port, host)
var net = require('net'),
querystring = require('querystring'),
http = require('http'),
port = 8383,
host = 172.123.321.213,
path = /path/toService,
_post = '';
var server = http.createServer(function(req, res) {
if(req.method == 'POST') {
req.on('data', function(data) {
body+=data;
});
req.on('end', function() {
_post = querystring.parse(body);//parser post data
console.log(_post);
})
}
var socket = net.createConnection(port, host);
var socket = net.createConnection(port, host);
socket.on('error', function(error) {
send404(res, host, port);
})
socket.on('connect', function(connect) {
console.log('connection established');
res.writeHead(200, {'content-type' : 'text/html'});
res.write('<h3>200 OK:
Connection to host ' + host + ' established. Pid = ' + process.pid + '</h3>\n');
res.end();
var body = '';
socket._writeQueue.push(_post);
socket.write(_post);
console.log(socket);
socket.on('end', function() {
console.log('socket closing...')
})
})
socket.setKeepAlive(enable=true, 1000);
}).listen(8000);
send404 = function(res, host, port) {
res.writeHead(404, {'content-type': 'text/html'});
res.write('<h3>404 Can not establish connection to host: ' + host + ' on port: ' + port + '</h3>\n');
res.end();
}
But now I need to send my data to the path defined - if I add the path to host then try connection then connection will fail.
但是现在我需要将我的数据发送到定义的路径 - 如果我将路径添加到主机然后尝试连接然后连接将失败。
Any ideas?
有任何想法吗?
Thanks in advance
提前致谢
回答by maerics
Your "socket" object is just a plain TCP socketwhich is just a simple bidirectional communication channel. The HTTP methods you're trying to use (e.g. res.writeHead()) don't pertain, so you'll have to write the request manually. Try something like this:
您的“套接字”对象只是一个普通的TCP 套接字,它只是一个简单的双向通信通道。您尝试使用的 HTTP 方法(例如res.writeHead())不相关,因此您必须手动编写请求。尝试这样的事情:
var socket = net.createConnection(port, host);
console.log('Socket created.');
socket.on('data', function(data) {
// Log the response from the HTTP server.
console.log('RESPONSE: ' + data);
}).on('connect', function() {
// Manually write an HTTP request.
socket.write("GET / HTTP/1.0\r\n\r\n");
}).on('end', function() {
console.log('DONE');
});

