【问题标题】:creating a tcp socket with net.createConnection(port, [host]) in node.js在 node.js 中使用 net.createConnection(port, [host]) 创建一个 tcp 套接字
【发布时间】:2016-06-15 16:00:42
【问题描述】:

这里的任何人都可以给我一些在 node.js 中使用套接字的指针吗?

可以在 172.0.0.1 的 8000 端口上打开一个 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();
  }

但现在我需要将我的数据发送到定义的路径 - 如果我将路径添加到主机然后尝试连接,那么连接将失败。

有什么想法吗?

提前致谢

【问题讨论】:

  • TCP 不做路径。 TCP 可以连接到(主机,端口)对。也许您想使用 HTTP?
  • 哦,另外,我假设您应该在写入套接字之前设置 on('end') 回调,以防它在写入期间结束。

标签: sockets node.js


【解决方案1】:

您的“socket”对象只是一个普通的TCP socket,它只是一个简单的双向通信通道。您尝试使用的 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');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 2011-05-18
    相关资源
    最近更新 更多