node.js中的http.createserver和net.createserver一起

问题描述

我在节点js中有2个脚本。一种使用“ http”,另一种使用“ net”。我想将这些脚本一起制作成一个脚本。我的“ http”脚本如下:

import React from 'react';
import { Provider } from 'react-native-paper';
import App from './src';
import { theme } from './src/core/theme';
import { NavigationContainer } from '@react-navigation/native';
import Drawer from './src/components/Drawer';
export default () => {
  
  return (
    <NavigationContainer>
      <Drawer />
    </NavigationContainer>
  );
};

'net'脚本:

const http = require('http');
const hostname = 'localhost';
const port = 3000;
const server = http.createServer((req,res) => {
 console.log(req.headers);
 res.statusCode = 200;
 res.end('<html><body><h1>Hello,World!</h1></body></html>');
})
server.listen(port,hostname);

我的目的是在启动“ http”脚本后运行“ net”脚本。

解决方法

将整个net script包装在导出的函数中:

var net = require('net');

module.exports = () => {
    var client = new net.Socket();
    client.connect(4352,'x.x.x.x',function() {
        console.log('Connected');
        client.write('%1POWR 1\r\n');
    });
    
    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');
    });
}

http script中导入并执行导出的函数:

const http = require('http');
const hostname = 'localhost';
const port = 3000;
require('path/to/net/script')() //Add to anywhere you like
const server = http.createServer((req,res) => {
 console.log(req.headers);
 res.statusCode = 200;
 res.end('<html><body><h1>Hello,World!</h1></body></html>');
})
server.listen(port,hostname);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...