Socket.io:ERR_CONNECTION_REFUSED

时间:2018-01-31 10:54:31

标签: node.js socket.io ionic2

我一直在打破这个问题一段时间,而且无法获得ERR_CONNECTION_REFUSED错误的解决方案。我确信我没有任何防火墙阻止该端口,如果我使用http://localhost:8080我收到回复。令我感到困惑的是,我还收到了这个错误"在收到握手响应之前关闭连接失败"。然后我重新启动了节点服务器并且该错误消失了,但仍然存在连接拒绝错误。请指教。

这是我的server.js

// set up ======================================================================
var path = require('path');
var app = require('express')();                     // create our app w/ express
var server = require('http').Server(app);
var mongoose = require('mongoose');                 // mongoose for mongodb
var port = process.env.PORT || 8080;                // set the port
//var database = require('./config/database');          // load the database config
var morgan = require('morgan');
var bodyParser = require('body-parser');
//var methodOverride = require('method-override');
var io = require('socket.io')(server);
var messageId = {};

// configuration ===============================================================
//mongoose.connect(database.localUrl);  // Connect to local MongoDB instance. A remoteUrl is also available (modulus.io)

//app.use(express.static('./public'));      // set the static files location /public/img will be /img for users
//app.use(morgan('dev')); // log every request to the console
//app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
//app.use(bodyParser.json()); // parse application/json
//app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
//app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request


// routes ======================================================================
//require('./app/routes.js')(app);

// listen (start app with node server.js) ======================================
//http://192.168.0.102:8080/
io.set('origins', '*:*');
io.on('connection', function (socket) {
    console.log('User Connected -- Server Online');   
    socket.on('message', function (msg,msgId) {
        io.emit('message', "Hello");
        console.log("message from client:", msg);
         setInterval(function(){
          io.emit("messageStatus",msgId);
      },500)
   });
});
app.get('/', function (req, res) {
    res.send('hello world')
})
app.listen(port);
console.log("App listening on port " + port);

这是我的客户(Ionic App)

import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams, Content } from 'ionic-angular';
import { ProfilePage } from '../profile/profile';
import { ActionSheetController } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
import * as io from 'socket.io-client';
import { File } from '@ionic-native/file';
declare var cordova : any
@Component({
  selector: 'page-userchat',
  templateUrl: 'userchat.html'
})
export class UserChatPage {
  @ViewChild(Content) content: Content;
  chatForm: FormGroup;
  chatValue: string;
  chatText: AbstractControl;
  messages = [];
  chatUserName: string;
  public currentDate: any;
  socket: any;
  public connectionError: string;
  iconId: string;
  msgId = []; 
  writeMessages = [];
  public userchatId : string;
  constructor(public navCtrl: NavController, public actionSheetCtrl: ActionSheetController, private fb: FormBuilder,
    private navParams: NavParams, private file: File) {
    this.chatForm = fb.group({
      'chatText': ['', Validators.compose([Validators.required])]
    })

    this.chatText = this.chatForm.controls['chatText'];
    this.chatUserName = navParams.get("name");
    this.userchatId = navParams.get("chatId");

    this.currentDate = (new Date()).toLocaleString('en-IN', { month: 'short', day: 'numeric', year: '2-digit', hour: 'numeric', minute: 'numeric', hour12: true });;
    this.socket = io('ws://localhost:8080', { transports: ['websocket'] })
    this.socket.on('message', (msg) => {
      this.messages.push({ "message": msg, "position": "text-left", "date": this.currentDate, "status": "", "icon-id": "" });     
      setTimeout(() => {
        this.content.scrollToBottom(300);//300ms animation speed
      });
    })
    this.socket.on('connect_error', (error) => {
      this.connectionError = "0";
    })

    this.socket.on('connect', () => {
      this.connectionError = "1";
      for (var i = 0; i < this.msgId.length; i++) {
        var el = document.getElementById(this.msgId[i]);
        if (!el) {
          el.classList.remove("iconf-exclamation");
          el.classList.add("iconf-check");
        }
      }
      this.socket.on("messageStatus", (msgId) => {
        var el = document.getElementById(msgId);
        if (el != null) {
          el.classList.remove("iconf-check");
          el.classList.remove("iconf-exclamation");
          el.classList.add("iconf-thumbs-up");
        }
      })
    })

1 个答案:

答案 0 :(得分:0)

这一行

this.socket = io('http://localhost:8080', { transports: ['websocket'] })

应该是

{{1}}