我正在使用node.js,socket.io和express处理聊天应用程序。我正在使用pm2来运行server.js。在日志上它说
0|server | 18-08 12:14:47.128: Server listening on port 3000
控制台中也没有错误。这是我的代码。请耐心等待我,因为我还是node.js和socket.io中的新手。每一个帮助都将受到高度赞赏。
server.js
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var app = require('express')();
var https = require('https');
var fs = require('fs');
var ssl_server_key = '/data/web/chat/app/node/server_key.pem';
var ssl_server_crt = '/data/web/chat/app/node/server_crt.pem';
var server = https.createServer({
key: fs.readFileSync(ssl_server_key),
cert: fs.readFileSync(ssl_server_crt),
NPNProtocols: ['http/2.0', 'spdy', 'http/1.1', 'http/1.0']
}, app);
var socket = require('socket.io');
var port = process.env.PORT || 3000;
var io = socket.listen(server);
server.listen(port, function () {
console.log('Server listening on port %d', port);
});
io.on('connection', function (socket) {
console.log('io connected');
socket.on('new message', function(data){
io.emit('push message', {msg: data.msg, sendername:data.sendername, sender:data.sender, receiver: data.receiver,profilepic:data.profilepic,email:data.email,picData:data.picData}) ;
console.log('new message from ', data.sendername);
});
socket.on('new announcement', function(data){
io.emit('push announcement', {msg: data.msg, title:data.title1, sendername:data.sendername, profilepic:data.profilepic});
});
socket.on('new email', function(data){
io.emit('push email', {receiver: data.receiver, sender:data.sender, email:data.email});
});
socket.on('disconnect',function(){
console.log('disconnected');
});
});
chatnew.js
$(function(){
var socket = io.connect('https://nd.gcoin.link:3000');
socket.heartbeatTimeout = 30000;
console.log('check 1', socket.connected);
socket.on('connect', function() {
console.log('check 2', socket.connected);
});
socket.on('disconnect', function(){
console.log('disconnected');
});
//var socket = io.connect();
socket.on('connect', function() {console.log('connect event');});
socket.on('connect_error', function(err) {console.log('connect error',err);});
socket.on('connect_timeout', function(err) {
console.log("client connect_timeout: ", err);
});
socket.on('push message', function(response){
var sender = $('#sender').val();
var sender2 = $('#sender2').val();
var receiver = $('#receiver').val();
var receiver2 = $('#receiver2').val();
var sendemail = $('#sendemail').val();
var email = $('#youremail').val();
var type = $('#type').val();
getLastID();
var last_id = $('#conv_id').val();
last_id = parseInt(last_id) + 1;
if(response.profilepic === 'n/a'){
var pic = '/user_images/no_image.jpg';
}else if(response.profilepic.substring(0, 4)=== 'https'){
var pic =response.profilepic;
}else if(response.profilepic === 'bot'){
var pic = '/user_images/bot.png';
}else{
var pic ='/user_images/'+response.profilepic;
}
console.log(response.picData);
console.log(response.picData.length);
if(sender == response.sender && response.receiver == receiver2 ){
updateLastView(response.sender,response.sender,type);
if(response.picData.length > 6){
//console.log(response.picData.length);
$('.chat').append('<li class="self"><div class="float-right"><div class="flex"><label style="" class="self-msg">' +response.msg+'<img src= "/images/uploaded/'+response.picData+'" class="msg-pic" onclick="imgEnlarge(this)" /></label><img src="'+pic+'" class="img-profile" onclick="imgEnlarge(this)" ></div><time data-livestamp="'+moment().unix()+'" class="msg-rhs" style="color: #c1c1c1;" ></time></div></li>');
}else{
$('.chat').append('<li class="self"><div class="float-right"><div class="flex"><label style="" class="self-msg">' +response.msg+'</label><img src="'+pic+'" class="img-profile" onclick="imgEnlarge(this)" ></div><time data-livestamp="'+moment().unix()+'" class="msg-rhs" style="color: #c1c1c1;" ></time></div></li>');
}
}else if(sender == response.receiver && response.sender == receiver2 ){
updateLastView(response.receiver,response.receiver,type);
if(response.picData.length > 6){
$('.chat').append('<li class="other"><div class="float-left"><div class="flex"><img src="'+pic+'" class="img-profile" onclick="imgEnlarge(this)" ><label style="" class="other-msg"> '+response.msg+'<img src= "/images/uploaded/'+response.picData+'" class="msg-pic" onclick="imgEnlarge(this)" /></label></div><time style="color: #c1c1c1;" data-livestamp="'+moment().unix()+'" class="msg-rhs" style="color: #c1c1c1;" ></time></div></li>');
}else{
$('.chat').append(' <li class="other"><div class="float-left"><div class="flex"><img src="'+pic+'" class="img-profile" onclick="imgEnlarge(this)"><label style="" class="other-msg"> '+response.msg+'</label></div><time style="color: #c1c1c1;" data-livestamp="'+moment().unix()+'" class="msg-rhs" style="color: #c1c1c1;" ></time></div></li>');
}
socket.emit('new email', { receiver: sender, sender: receiver,email:email });
}
$("html, body").animate({ scrollTop: $(document).height() }, 1000);
});
$(document).on('keyup','.message-box',function(e){
var message = $('.message-box').val();
var $this = $(this);
var len = $(this).val().length;
//console.log('len:'+len);
if(len == 0){
document.getElementById("submit").disabled = false;
$("#submit").removeClass('disabled');
}
document.getElementById("submit").disabled = false;
$("#submit").removeClass('disabled');
// bot(message);
});
//image upload
document.getElementById("file-upload").onchange = function() {
//document.getElementById("formpic").submit();
var message = '';
var sender = $('#sender').val();
var sendername = $('#sendername').val();
var receiver = $('#receiver').val();
var receiver2 = $('#receiver2').val();
var type = $('#type').val();
var profilepic = $('#profilepic').val();
var email = $('#email').val();
var pic = $("#file-upload").val();
var pic = pic.replace(/^.*\\/, "");
var picData = $("#image_data").val();
var file_data = $('#file-upload').prop('files')[0];
var hash = makehash();
var filename = hash + '_'+ pic;
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('hash', hash);
form_data.append('message', message);
form_data.append('sender', sender);
form_data.append('receiver', receiver);
form_data.append('type', type);
console.log(type);
console.log(receiver);
console.log(sender);
var server_name = $("#server_name").val();
$('#loading-image').show();
$.ajax({
url: '//'+server_name+'/base__upchat/',
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(x){
// alert(x); // display response from the PHP script, if any
if(x == 1){
socket.emit('new message', { msg: message, sender: sender,sendername:sendername, receiver:receiver2,picData:filename,profilepic:profilepic,email:email });
}
console.log('success:'+x);
},
complete: function(){
$('#loading-image').hide();
}
});
$('#file-upload').val('');
//updateLastView(sender,sender,type);
//getLastID();
};
// make hash for image upload
function makehash()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
// send message
$('.btn-send').on('click',function(){
var div = document.getElementById('submit');
var message = $('.message-box').val();
var sender = $('#sender').val();
var sender2 = $('#sender2').val();
var sendername = $('#sendername').val();
var receiver = $('#receiver').val();
var receiver2 = $('#receiver2').val();
var type = $('#type').val();
var profilepic = $('#profilepic').val();
var email = $('#email').val();
var pic = $("#file-upload").val();
var pic = pic.replace(/^.*\\/, "");
var picData = $("#image_data").val();
var file_data = $('#file-upload').prop('files')[0];
var hash = makehash();
var filename = hash + '_'+ pic;
if( message ==''){
$('.validation').text('不正な文字が入力されました').fadeIn();
$('#submit').prop('disabled','true').addClass('disabled');
//$('.send').removeClass('btn-send');
}else {
validateWords();
var check = checkWords(message);
if (check == true){
//alert('bad');
$("#characters").text('不正な文字が入力されました').css('color','red');
//alert('不正な文字が入力されました');
$('#submit').prop('disabled','true').addClass('disabled');
}else{
document.getElementById("submit").disabled = false;
$("#submit").removeClass('disabled');
//console.log('message:'+validateEmail(message));
if(validateEmail(message) == true ){
//console.log('message:'+validateEmail(message));
$("#characters").text('不正な文字が入力されました').css('color','red');
//alert('不正な文字が入力されました');
$('#submit').prop('disabled','true').addClass('disabled');
}else{
document.getElementById("submit").disabled = false;
$("#submit").removeClass('disabled');
if(phonenumber(message) == true ){
$("#characters").text('不正な文字が入力されました').css('color','red');
//alert('不正な文字が入力されました');
$('#submit').prop('disabled','true').addClass('disabled');
}else{
document.getElementById("submit").disabled = false;
$("#submit").removeClass('disabled');
$('.message-box').val('');
var botdb ='0';
updateDB(receiver,sender,message,type,email,botdb); //Update message in DB
$('#characters').text('130/130').css('color','#333');
socket.emit('new message', { msg: message, sender: sender,sendername:sendername, receiver:receiver2,picData:filename,profilepic:profilepic,email:email });
$('.validation').css({"display":"none"});
bot(message,receiver,sender,type,email,sendername,receiver2,filename,profilepic,sender2);
/* var bot_reply = $("#bot_reply").val();
alert(bot2(message));
console.log('bot_reply:'+bot_reply);*/
//bot(message);
/*var bot_reply2 = $("#bot_reply").val();
alert(bot_reply2);*/
}
}
}
}
});
// validating input for email entry
function validateEmail(elementValue)
{
// var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var emailPattern = /[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}/igm;
var patt = new RegExp(emailPattern);
return patt.test(elementValue);
}
// validating input for phone number entry
function phonenumber(inputtxt) {
//var numberPattern = /^\(?([0-9]{3})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/
var numberPattern = /\(?([0-9]{3})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})/igm;;
var patt = new RegExp(numberPattern);
return patt.test(inputtxt);
}
// validating input for bad words entry
function checkWords(message) {
var my_textarea = $('.message-box').val().toLowerCase();
var pattern1 = $('#bad').val();
var patt = pattern1.split("|");
if(hasWhiteSpace(my_textarea) == true ){
var res = my_textarea.split(" ");
for (i = 0; i < res.length; i++) {
for (i2 = 0; i2 < patt.length; i2++) {
switch(res[i]){
case 'anal':
case patt[i2]:
return true;
break;
}
}
}
}else{
for (i2 = 0; i2 < patt.length; i2++) {
switch(my_textarea){
case 'anal':
case patt[i2]:
return true;
break;
}
}
}
}
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
//inserting message to db
function updateDB(receiver,name,msg,type,email,botdb){
console.log('receiver:' + receiver);
console.log('name:' + name);
console.log('msg:' + msg);
console.log('type:' + type);
console.log('email:' + email);
console.log('botdb:' + botdb);
$.post('/base__process/',{method:'update',receiver:receiver,sender:name,msg:msg,type:type,email:email,botdb:botdb},function(response){
// alert(response);
var pic1 = JSON.parse(response);
//$('.uspoints').text(number_format(pic1.pt,'.','.',',')+' PTS.');
console.log('response:' + response);
});
}
function bot(msg,receiver,sender,type,email,sendername,receiver2,filename,profilepic,sender2){
var type ='0';
var botdb ='1';
$.post('/base__process/',{method:'bot_reply',msg:msg},function(reps){
console.log('bot:'+reps);
var dt = JSON.parse(reps);
console.log('msg: '+msg);
console.log('botrep:'+dt.reply);
console.log('botmsg:'+dt.msg);
if(dt.msg == msg){
$("#bot_reply").val(dt.reply);
/* var rep = dt.rep;
return rep;*/
// alert( $("#bot_reply").val());
var bot_reply = $("#bot_reply").val();
if(bot_reply != 'n/a'){
updateDB(sender2,receiver2,bot_reply,type,email,botdb); //Update message in DB
$('#characters').text('130/130').css('color','#333');
socket.emit('new message', { msg: bot_reply, sender: receiver2,sendername:sendername, receiver:sender,picData:filename,profilepic:'bot',email:email });
$('.validation').css({"display":"none"});
}
}else{
$("#bot_reply").val('n/a');
/*var rep = 'n/a';
return rep;*/
// alert( $("#bot_reply").val());
}
});
}
function number_format (number, decimals, dec_point, thousands_sep) {
// Strip all characters but numerical ones.
number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function (n, prec) {
var k = Math.pow(10, prec);
return '' + Math.round(n * k) / k;
};
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
// fetching bad words
function validateWords()
{
$.post('/base__process/',{method:'validateWords'},function(reps){
$("#bad").val(reps);
// console.log(reps);
});
}
// updating message last view
function updateLastView(sender,receiver,type){
$.post('/base__process/',{method:'updateLastView',sender:sender,receiver:receiver,type:type},function(response){
var pic1 = JSON.parse(response);
});
}
//getting last insert id in message
function getLastID(){
$.post('/base__process/',{method:'getLastID'},function(response){
var pic1 = JSON.parse(response);
console.log('last:'+pic1.conv_id);
$('#conv_id').attr('value', pic1.conv_id);
});
}
});
$(function() {
//Pretty Photo
$("a[rel^='prettyPhoto']").prettyPhoto({
social_tools: false
});
$('#input').keypress(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
$('#input').keyup(updateCount);
$('#input').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
var cs2 = 130 - cs;
var cs3 = 130 - cs+'/130';
if(cs2 <= 5){
$('#characters').text(cs3).css('color','red');
}else{
$('#characters').text(cs3).css('color','#333');
}
}
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("input"));
});
Edit1:尝试以下但没有运气
Node.js Socket.IO not working completely
编辑2: 此错误显示:
connect error Error: xhr poll error
Stack trace:
[14]</n.prototype.onError@https://gcoin.link/js/socket.io.js:719:25
[17]</</o.prototype.doPoll/<@https://gcoin.link/js/socket.io.js:885:25
[9]</n.prototype.emit@https://gcoin.link/js/socket.io.js:419:63
[17]</</i.prototype.onError@https://gcoin.link/js/socket.io.js:921:21
[17] </</i.prototype.create/e.onreadystatechange/<@https://gcoin.link/js/socket.io.js:907:33
添加后:
socket.on('connect_error', function(err) {console.log('connect error',err);});
试过这些:
How configure reconnecting in socket.io?
Controlling the heartbeat timeout from the client in socket.io
但错误:连接错误错误:xhr轮询错误仍然显示
这些脚本加载到ch002.html
<script src="/js/chatnew.js" ></script>
<script src="/js/socket.io.js"></script>