在Debian上使用Node.js实现跨平台通信,可以采用多种方法。以下是一些常见的实现方式:
WebSocket是一种在单个TCP连接上进行全双工通信的协议。Node.js有多个库可以用来实现WebSocket,比如ws
和socket.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>
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();
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');
});
消息队列是一种异步通信机制,常见的消息队列系统有RabbitMQ、Kafka和Redis。
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);
以上是几种常见的跨平台通信方式,可以根据具体需求选择合适的方法。