dongxieting9623 2019-06-05 10:18
浏览 153

io.emit工作正常,socket.emit在socket.io和node.js聊天应用程序中不起作用

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
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥50 永磁型步进电机PID算法
    • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
    • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
    • ¥15 如何处理复杂数据表格的除法运算
    • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
    • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
    • ¥200 uniapp长期运行卡死问题解决
    • ¥15 latex怎么处理论文引理引用参考文献
    • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
    • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?