我是节点js和socket.io的新手,我在我的windows机器上尝试socket.io的基本示例.
服务器代码
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Run Code Online (Sandbox Code Playgroud)
客户代码
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080/');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
socket.on('connect', function () {
alert('connect');
});
socket.on('error', function (data) {
console.log(data || 'error');
});
socket.on('connect_failed', function (data) {
console.log(data || 'connect_failed');
});
</script>
Run Code Online (Sandbox Code Playgroud)
在上面的脚本中,客户端无法连接到服务器(在控制台中记录了connect_failed),但同时显示了服务器端的后续内容,
info - socket.io started
debug - served static content /socket.io.js
debug …Run Code Online (Sandbox Code Playgroud)