I've setup a very simple chat application using node.js and socket.io. Everything works fine when the server broadcasts via io.emit (clients receiving data), but when switching to socket.emit, the originating client does not receive any data. I'm using CodeIgniter for the framework and using the form to post data to a MySQL DB, which works fine as well. The only problem is the socket.emit not working as expected. Below is my code:
I've already tried with all possible emit functions provided by the socket.io documentation and went through all the related pages on SO, but nothing works. I've also re-installed socket.io on my ubuntu server, but nothing changes
//Server.js code:
var fs = require('fs');
var app = require('express')();
var options = {key: fs.readFileSync('/etc/ssl/private/private.pem'), cert: fs.readFileSync('/etc/ssl/certs/public.pem')};
var server = require('https').Server(options, app);
var io = require('socket.io').listen(server);
server.listen(3000, function () {
console.log("service running on port 3000");
});
io.sockets.on('connect', function (socket) {
console.log('client id '+socket.id+' connected');
socket.on('join', function (data) {
var room_no = 'room'+data.room;
socket.join(room_no);
console.log('joined room no.:', data.room);
});
socket.on('disconnect', function(){
console.log("client "+socket.id+" disconnected");
});
socket.on('send message', function(post) {
socket.emit('privatemsg', post);
console.log('sending message "'+post.message+'" to:'+socket.id);
});
socket.on('error', function (err) {
console.log(err);
});
});
//Client code (codeigniter):
<?php
$this->load->view('templates/headers/main_header', $title);
?>
<div class="container">
<div class="row">
<div class="pull-left">
<h3><?php echo $page->title; ?></h3>
</div>
</div>
<?php echo form_open('user/sendmsg', array ('name'=>'message','method'=>'post')); ?>
<div class="container">
<div class="col-md-3">
<p>
<input type="text" placeholder="Type Here..." class="form-control" size="20px" id="message" name="message" />
</p>
<input type="hidden" id="conversation_id" name="conversation_id" value="1" />
</div>
<div class="col-md-3">
<input type="button"class="btn btn- primary"id="send"name="send"value="Send"/>
</div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>From</th>
<th>Message</th>
</tr>
</thead>
<tbody id="message-tbody">
<?php foreach($allMsgs as $row) { ?>
<tr><td><?php echo $row['msgtime']; ?></td><td><?php echo $row ['user2']; ?></td><td><?php echo $row['message']; ?></td></tr>
<?php } ?>
</tbody>
</table>
</div>
<?php echo form_close();?>
<script src="<?php echo base_url('js/jquery-3.3.1.min.js');?>"></script>
<script src="<?php echo base_url('chatjs/node_modules/socket.io- client/dist/socket.io.js');?>"></script>
<script>
$(document).ready(function(){
$(document).on("click","#send",function() {
var dataString = {
message : $("#message").val(), conversation_id:$("#conversation_id").val()
};
$.ajax({
type: "POST",
url: "<?php echo base_url('user/sendmsg');?>",
data: dataString,
dataType: "json",
cache : false,
success: function(data){
if(data.success ==true){
console.log("data:"+JSON.stringify(data));
var socket = io.connect ( 'https://'+window.location.hostname+':3000' );
socket.emit('send message', {
message: data.message,
date: data.date,
user2: data.user2
});
console.log("socket msg sent")
}
} ,error: function(xhr, status, error) {
console.log(error);
},
});
});
});
var socket = io.connect( 'https://'+window.location.hostname+':3000', {secure: true});
socket.on('connect', function(socket) {
console.log('client connected');
});
socket.on('error', function (err) {
console.log(err);
});
socket.on('privatemsg', function(msg) {
console.log("data received:"+JSON.stringify(msg));
$("#message-tbody").prepend ('<tr><td>'+msg.date+'</td><td>'+msg.user2+'</td><td>'+msg.message+'</td></tr >');
});
</script>
</div>
<?php
$this->load->view('templates/footers/main_footer');
?>
//node.js console.log:
// root@localhost:/var/www/html/chatjs# node server.js
// service running on port 3000
// client id nK5BmZwg0mQQWzv6AAAA connected
// client id qpKyI2WTRXL60EoqAAAB connected
// sending message "test444" to:qpKyI2WTRXL60EoqAAAB$
//Client (Chrome) console.log:
// ial.js:3219 registerEventsMessage called
// ial.js:4459 ready: before call parse for last time > Object
// client connected
// uchat:240 msg:{"message":"test444","conversation_id":"1"}
// uchat:250 data: {"message":"test444","conversation_id":"1","date":"2019-06-05 10:10:10","user1":2,"user2":3,"status":1,"success":true}
// uchat:257 socket msg sent