dpba63888 2015-06-24 08:04
浏览 697

可以在nodeJS中调用Socket.on()

I want to use nodeJS in my PHP web app. I followed the nodejs tutorial and that works fine when I run on localhost:3000 but I want to run on url like this localhost/final/chat/chat_index.html file. So What I did is following code

chat_index.html

<div id="newUser">
  <form id="user">
    <input id="username">
    <input type="submit">
  </form>
</div> 
$(document).ready(function(){
var socket = io.connect('http://localhost:3000/final/chat/chat_index.html',
                        {resource:'https://cdn.socket.io/socket.io-1.2.0.js'});

$('#user').submit(function(){
socket.emit('new user', $('#username').val());
});

}); // document.ready ends here
</script>

index.js This is server side JS file

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);


app.get('/final/chat/chat_index.html', function(req, res){
  res.sendFile(__dirname + '/chat_index.html');
});



io.on('connection', function(socket){
   console.log('connected user');

   socket.on('new user', function(user){
       console.log(user);
   });  
});

http.listen(3000, function(){
 console.log('listening to port');
});

Above chat_index.html page loads which shows the form on it. When I submit some data through this form server side js is not getting the data.

Is something missing in my code or I am doing something wrong in my code. Thanks in advance

  • 写回答

2条回答 默认 最新

  • dqm4977 2015-06-24 08:42
    关注

    Which version of express are you using? I believe in express 4 it should be:

    var http = require('http').createServer(app);
    

    On the client side could you also try using:

    var socket = io.connect();
    

    then load the resource in as a script tag?

    评论

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?