所以我安装了 SocketCAN、Express 和 Socket.io 节点模块。
我想要做的是: *通过 Express 服务器上的 Socket.io 初始化一个 Socket *使用服务器上的 socketCAN“node-can”模块将消息发送到我的前端(Angular6)
到目前为止我所做的:
*创建了一个 Express 服务器并初始化了 Socket.io 和 node-can 那里 *能够在我的应用程序中连接到我的套接字
这是实现此目的的代码:
const express = require('express');
const path = require('path');
const http = require('http');
const socketIO = require('socket.io');
var can = require('socketcan');
var channel = can.createRawChannel("vcan0", true);
channel.start();
const app = express();
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'dist/akkaDiagTool')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/akkaDiagTool/index.html'));
});
const server = http.createServer(app);
const io = socketIO(server);
io.on('connection', (socket) => {
console.log('socket connected');
socket.on('can message', (from, msg) => {
msg.channel.addListener("onMessage", function(data) {console.log(data);});
console.log('Recieved message by', from , 'sayin ', msg);
});
socket.on('disconnected', (socket) => {
console.log('socket disconnected');
})
})
server.listen(port, () => {
console.log(`Server running on port ${port}`)
})
因此,当我启动我的应用程序并使用 socketcan 发送 can 消息时:cansend vcan0 37F#0000000012343412
我只会看到我的日志msg.channel.addListener("onMessage", function(data) {console.log(data);});
但不是console.log('Recieved message by', from , 'sayin ', msg);
日志
我的 Angular 组件如下所示:
import { Component, OnInit } from '@angular/core';
import * as io from 'socket.io-client';
@Component({
.
.
.
})
export class StaticDataComponent implements OnInit {
socket;
constructor() {
this.socket = io();
this.socket.on('can message', (data) => {
console.log(data);
});
}
应该连接套接字,因为我socket connected
在控制台中获得了日志。
任何帮助,将不胜感激
提前谢谢。