2015-06-24 53 views
0

我想在我的PHP Web應用程序中使用nodeJS。我遵循nodejs教程,並且在localhost:3000上運行時工作正常,但我想在url上運行,就像這個localhost/final/chat/chat_index.html文件一樣。所以我所做的是下面的代碼可以在nodeJS中調用Socket.on():解決方案

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這是服務器端的JS文件

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.of('/final/chat/chat_index.html').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'); 
}); 

以上chat_index.html頁面加載,顯示在窗體它。當我通過這個表單服務器端提交一些數據時,js沒有獲取數據。

在我的代碼中缺少某些東西,或者我在代碼中做錯了什麼。 在此先感謝

+0

問題解決了'io.of('/ final/chat/chat_index.html')'應該在'io'方法之前使用 –

回答

0

您正在使用哪種版本的快遞?我相信,在快遞4應該是:

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

在客戶端可能也嘗試使用:

var socket = io.connect(); 

然後在加載資源作爲腳本標籤?

1

如果您希望在特定的航線上運行的插座,您可以使用房/命名空間

http://socket.io/docs/rooms-and-namespaces/#

實例(服務器)

var finalChat = io.of("/final/chat"); 
finalChat.on('connection', function(socket){ 
    console.log('connected user'); 

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

如果你想獨立的私人聊天室,你可能想用id底座套房

+0

這就是我在我的代碼中所做的事情請參閱評論和編輯的問題。無論如何感謝您的幫助 –

相關問題