如何使用Vue.js,Socket.io,Arduino与客户端的服务器连接?

时间:2017-08-16 15:40:03

标签: http webpack socket.io arduino vue.js

我的客户端应用程序连接服务器有问题。我希望通过Vue.js编写的客户端与我的Arduino板连接并进行控制。

我有一台运行在node.js上的服务器,运行良好。

const http = require('http');
const socketIo = require('socket.io');
const port = process.env.PORT || 5000;
const server = http.createServer().listen(port, () => { });
const five = require('johnny-five');
const board = new five.Board();
const pin = {
  13: {
    led: {
      on: () => console.log('on'),
      off: () => console.log('off'),
    },
  },
};    
const io = socketIo(server);

board.on('ready', () => {
  const led = new five.Led(13);
  led.off();
  pin[13].led = led;
});

io.sockets.on('connection', (socket) => {
  socket.on('message', (channel, message) => {
    if (channel === 'on') pin[message].led.on();
    if (channel === 'off') pin[message].led.blink(500);
  });
});

但是我遇到了客户端问题。这是我的代码,我不知道我现在能做什么。

<template>
  <router-view>
  </router-view>
</template>

<script>
import Vue from 'vue';
import VueRouter from 'vue-router/dist/vue-router';

import LoginRoutes from 'features/login/login.routes';
import FoobarRoutes from 'features/foobar/foobar.routes';

import 'common/components'; 
import Jquery from 'jquery';

import BootstrapCSS from 'bootstrap/dist/css/bootstrap.css';
import Bootstrap from 'bootstrap';

Vue.use(VueRouter);

io = require("socket.io/lib/socket");
var socket = io.connect("http://localhost:5000");

const routes = [
  {
    path: '/',
    redirect() {
      return '/login';
    },
  },
  ...LoginRoutes,
  ...FoobarRoutes,
];


const router = new VueRouter({
  routes,
});

export default {
  router,
};
</script>

这是我的观点:

<template>
  <div>
        <h1>TURN ON/OFF LED</h1>
        <button class="btn btn-danger" @click='on'>13: ON</button>
        <br><br>
        <button @click='off'>13: OFF</button>
  </div>
</template>

<script>
export default {
  name: 'login-view',
  methods: {
    on: function() {
      socket.send('on', 13);
      // this.$socket.emit('on', 13);
    },
    off: function() {
      socket.send('off', 13);
    },
  },
};
</script>

<style>
</style>

1 个答案:

答案 0 :(得分:0)

您在客户端使用了错误的模块,请使用socket.io-client,例如:

var sio = require('socket.io-client')
var socket = sio('http://localhost:5000')