debian

Node.js在Debian上如何实现跨平台通信

小樊
36
2025-06-19 12:52:57
栏目: 编程语言

在Debian上使用Node.js实现跨平台通信,可以采用多种方法。以下是一些常见的实现方式:

1. 使用WebSocket

WebSocket是一种在单个TCP连接上进行全双工通信的协议。Node.js有多个库可以用来实现WebSocket,比如wssocket.io

安装ws

npm install ws

示例代码

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

客户端代码(浏览器)

<!DOCTYPE html>
<html>
<head>
  <title>WebSocket Test</title>
</head>
<body>
  <script>
    const socket = new WebSocket('ws://localhost:8080');

    socket.onopen = function() {
      socket.send('Hello Server!');
    };

    socket.onmessage = function(event) {
      console.log('Message from server:', event.data);
    };
  </script>
</body>
</html>

2. 使用HTTP/HTTPS

Node.js内置了HTTP和HTTPS模块,可以用来创建HTTP服务器和客户端。

示例代码(服务器)

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World\n');
});

server.listen(8080, () => {
  console.log('Server running at http://localhost:8080/');
});

示例代码(客户端)

const http = require('http');

const options = {
  hostname: 'localhost',
  port: 8080,
  path: '/',
  method: 'GET'
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

req.end();

3. 使用TCP/IP

Node.js的net模块可以用来创建TCP服务器和客户端。

示例代码(服务器)

const net = require('net');

const server = net.createServer((socket) => {
  socket.write('Echo server\r\n');

  socket.on('data', (data) => {
    console.log(`Received: ${data}`);
    socket.write(data);
  });

  socket.on('end', () => {
    console.log('Client disconnected');
  });
});

server.listen(8080, () => {
  console.log('Server listening on port 8080');
});

示例代码(客户端)

const net = require('net');

const client = net.createConnection({ port: 8080 }, () => {
  console.log('Connected to server');
  client.write('Hello, Server!');
});

client.on('data', (data) => {
  console.log(`Received: ${data}`);
  client.end();
});

client.on('close', () => {
  console.log('Connection closed');
});

4. 使用消息队列

消息队列是一种异步通信机制,常见的消息队列系统有RabbitMQ、Kafka和Redis。

安装RabbitMQ

sudo apt-get update
sudo apt-get install rabbitmq-server

示例代码(生产者)

const amqp = require('amqplib');

async function sendMessage() {
  const conn = await amqp.connect('amqp://localhost');
  const channel = await conn.createChannel();
  const queue = 'hello';

  await channel.assertQueue(queue, { durable: false });
  const message = 'Hello World!';
  channel.sendToQueue(queue, Buffer.from(message));
  console.log(" [x] Sent %s", message);

  setTimeout(() => {
    channel.close();
    conn.close();
  }, 500);
}

sendMessage().catch(console.warn);

示例代码(消费者)

const amqp = require('amqplib');

async function receiveMessage() {
  const conn = await amqp.connect('amqp://localhost');
  const channel = await conn.createChannel();
  const queue = 'hello';

  await channel.assertQueue(queue, { durable: false });
  console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queue);
  channel.consume(queue, (msg) => {
    const message = msg.content.toString();
    console.log(" [x] Received %s", message);
    channel.ack(msg);
  });
}

receiveMessage().catch(console.warn);

以上是几种常见的跨平台通信方式,可以根据具体需求选择合适的方法。

0
看了该问题的人还看了