伙计们,我正在尝试使用net.Socket软件包制作简单的TCP服务器,而我正在使用Express框架。 我试图实现的行为是,当用户输入特定的路由向所有连接的客户端发送数据时,现在有人没有办法实现这一目标吗?
这是我的示例代码:
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const net = require('net');
const PORT = 5000;
let connection;
const server = net.createServer((socket) => {
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
connection = socket;
});
app.use(cors());
app.use(bodyParser.json());
app.get('/', (request, response) => {
response.send('VMS server');
});
app.post('/contact', (req, res) => {
const data = { hello: 'hello' }
connection.write(data);
res.send({ data: 'data emmited' })
});
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
server.listen(1337, function() {
console.log("Listening on 1337");
});
这里的问题是,由于我将当前套接字分配给连接变量,因此数据多次发射。
还有其他方法可以实现吗,我可以使用服务器变量以某种方式向所有连接的客户端发出信号吗?
答案 0 :(得分:0)
好,设法解决了。以下是有关如何解决此问题的步骤-创建一个客户端数组,以及当客户端连接到服务器时,在断开连接时将该套接字推入客户端数组,然后从阵列中删除该项目...并向所有客户端发出数据创建了一个广播方法,让我遍历客户端数组,并调用每个套接字的emit方法并发送数据。
这是示例代码:
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const net = require('net');
const PORT = 5000;
let sockets = []; // array of sockets
// emmit data to all connected clients
const broadcast = (msg) => {
//Loop through the active clients object
sockets.forEach((client) => {
client.write(msg);
});
};
const server = net.createServer((socket) => {
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
sockets.push(socket);
socket.on('end', () => {
console.log('DISCONNECTED: ');
// remove the client for list
let index = sockets.indexOf(socket);
if (index !== -1) {
console.log(sockets.length);
sockets.splice(index, 1);
console.log(sockets.length);
}
});
});
app.use(cors());
app.use(bodyParser.json());
app.get('/', (request, response) => {
response.send('VMS server');
});
app.post('/contact', (req, res) => {
const data = { hello: 'hello' }
broadcast(data); //emit data to all clients
res.send({ data: 'data emmited' })
});
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
server.listen(1337, function() {
console.log("Listening on 1337");
});