简体   繁体   中英

Socket IO on Angular2

im trying to use socket io connected to angular 2 with newest release package, i've download it from angular2/quickstart-master

i've put this script on index.html

<script src="socket.io/socket.io.js"></script>

and then im creating server,

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();

var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
io.set("origins", "*:*");

var currentPrice = 99;

io.on('connection', function (socket) {
    socket.emit('priceUpdate',currentPrice);
    socket.on('bid', function (data) {
        currentPrice = parseInt(data);
        socket.emit('priceUpdate',currentPrice);
        socket.broadcast.emit('priceUpdate',currentPrice);
    });
});

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'app')));

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

module.exports = app;

and put socket io on component,

price: number = 0.0;
    socket : any;
    bidValue = '';

constructor() { 
            this.socket = io('http://localhost:8000');  **<< on this part**
            this.socket.on('priceUpdate', function(data){
            this.price = data;
        }.bind(this));    
        }

    bid(){
        this.socket.emit('bid', this.bidValue);
        this.bidValue = '';
    }

but i've got an error saying that could not find io,

any things wrong with my code?

在导入后添加declare var io:any

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM