我已经为此打破了一段时间,无法ERR_CONNECTION_REFUSED找到此错误的解决方案。我确定我没有任何防火墙阻止端口,如果我使用 http://localhost:8080 我会得到响应。令我困惑的是,我还收到此错误"在收到握手响应之前关闭连接失败"。然后我重新启动了节点服务器,该错误消失了,但连接拒绝错误仍然存在。请指教。
这是我的服务器.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);
这是我的客户端(离子应用程序(
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");
}
})
})
此行
this.socket = io('ws://localhost:8080', { transports: ['websocket'] })
应该是
this.socket = io('http://localhost:8080', { transports: ['websocket'] })