[英]SocketCAN + Express.js + Node.js + Socket.io
因此,我已经安装了SocketCAN,Express和Socket.io节点模块。
我想做的是:*通过Express服务器上的Socket.io初始化一个套接字*使用服务器上的socketCAN“ node-can”模块将消息发送到我的前端(Angular6)
到目前为止,我所做的是:
*创建一个Express服务器并初始化Socket.io和节点-可以在那里*能够连接到我的App中的套接字
这是实现此目的的代码:
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);});
的日志msg.channel.addListener("onMessage", function(data) {console.log(data);});
但不是console.log('Recieved message by', from , 'sayin ', msg);
日志
我的角度组件看起来像这样:
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
日志。
任何帮助,将不胜感激
提前谢谢。
好吧,我设法弄清楚了。
我必须在服务器上的socket.io的socket.emit内使用io.emit():
io.on('connection', (socket) => {
//create canChannel with socketcan(node-can)
var channel = can.createRawChannel('vcan0', true);
//emit messagees to the *can message* listening to the canChannel
socket.emit('can message', channel.addListener('onMessage', (data) => {
io.emit('can message', data);
}));
channel.start();
//disconnect
socket.on('disconnected', (socket) => {
console.log('socket disconnected');
});
这里是Angular组件中的代码:
constructor() {
this.socket = io();
this.socket.on('can message', (msg) => {
console.log('data', msg);
});
}
提供的代码非常简单,只需在开发人员控制台中登录数据即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.