vue+node express生成器 使用socket.io (websocket)

1.客户端(前端) Index.html引入服务 socket脚本


然后 我的是点击连接websockt

handleClick(){
           var socket=io("ws://192.168.1.80:3000");
                   socket.on('chat message', function(msg){
                     console.log(msg)
                   })
    }

服务端先安装

npm install --save socket.io

APP.js 不用管 现在是为websocket开服务

服务端 在bin目录下www里面

//添加的socket代码
var io = require('socket.io').listen(server);

io.on('connection', function(socket){
  console.log('a user connected234');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});


以下是我全部的www代码

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('myapp:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

//添加的socket代码
var io = require('socket.io').listen(server);

io.on('connection', function(socket){
  console.log('a user connected234');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}


然后重启服务 点击事件 会看到你服务端窗口打印 OK

你可能感兴趣的:(VUE,node,Node+express,soket.io,websocket)