我正在尝试在.php页面上的socket.io和node.js服务器之间建立一个简单的连接,但不幸的是它不会工作? .on('connection')不会在服务器端代码上触发?
我看到的所有问题都表达了,我不想用快递..
客户方:
<script src="https://cdn.socket.io/socket.io-1.4.7.js"></script>
<script>
var socket = new io.connect('http://127.0.0.1:1904');
socket.on('connect', function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message', function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect', function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
};
</script>
服务器端:
var http = require('http');
var server = http.createServer();
server.listen(1904);
console.log('Server started.');
var io = require('socket.io')(server, {});
io.sockets.on('connecton', function(socket) {
console.log('A new player connected.');
socket.on('happy', function(data) {
console.log('happy because: ' + data.reason);
})
});
答案 0 :(得分:0)
这是我用于所有基于套接字的节点项目的例程,希望这可以帮到你。如果您有任何其他我可以帮助的问题,请与我们联系。
名为server.js的文件:
var http = require('http').Server();
var io = require('socket.io')(http);
http.listen(3001, function(){
console.log('listening on *:3001');
});
//for testing, we're just going to send data to the client every second
setInterval( function() {
var msg = Math.random();
io.emit('message', msg);
console.log (msg);
}, 1000);
名为index.html的文件:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<!-- UPDATE THE FOLLOWING TO THE PATH TO YOUR SOCKET.IO.JS FILE OR USE CDN -->
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
$('body').css('width', '100%');
$('div').css('text-align', 'center').css('width', '100%')
$('#message').css('font-size', '2em');
// DEFINE OUR SOCKET...
var socket = io();
// EVERY TIME THE NODE.JS SERVER SENDS US 'MESSAGE' WE'LL DISPLAY THAT UPDATED NUMBER IN A DIV
socket.on('message', function(msg){
document.getElementById("message").innerHTML = msg;
});
</script>
</head>
<body>
<div id="message"></div>
</body>
</html>