Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了套接字 – 在node.js中使用net.createConnection(port,[host])创建一个tcp套接字大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这里的任何人都可以给我一些使用Node.js中套接字的指针吗?

可以在端口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,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();
  }@H_874_10@ 
 

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

有任何想法吗?

提前致谢

解决方法

你的“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');
});@H_874_10@

大佬总结

以上是大佬教程为你收集整理的套接字 – 在node.js中使用net.createConnection(port,[host])创建一个tcp套接字全部内容,希望文章能够帮你解决套接字 – 在node.js中使用net.createConnection(port,[host])创建一个tcp套接字所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。