javascript - socket.io not working no error shows -
i'm working on chat application using node.js,socket.io , express. i'm using pm2 run server.js . on log says
0|server | 18-08 12:14:47.128: server listening on port 3000
there no error in console either. codes . please bear me i'm still newbie in node.js , socket.io. every highly appreciated.
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 ', 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 php script, if 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 image upload function makehash() { var text = ""; var possible = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; < 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 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 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 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(" "); (i = 0; < res.length; i++) { (i2 = 0; i2 < patt.length; i2++) { switch(res[i]){ case 'anal': case patt[i2]: return true; break; } } } }else{ (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 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 characters 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 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: tried following no luck
node.js socket.io not working completely
edit 2: error show :
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
after adding :
socket.on('connect_error', function(err) {console.log('connect error',err);});
tried these:
how configure reconnecting in socket.io?
controlling heartbeat timeout client in socket.io
but error : connect error error: xhr poll error still shows
these scripts loaded ch002.html
<script src="/js/chatnew.js" ></script> <script src="/js/socket.io.js"></script>
Comments
Post a Comment