我正在尝试使用socket.io处理html页面和http服务器之间的请求无法POST / [HTTP / 1.1 404未找到1ms] 服务器代码:
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.3.4.js">
var socket = io('http://localhost');
console.log(socket);
socket.emit('registration',"test");
</script>
</head>
<body>
html页面如下
Parse error: syntax error, unexpected '.', expecting '&' or variable (T_VARIABLE) in /path/site/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 475
答案 0 :(得分:0)
创建package.json文件:
{
"name": "socket.io-test",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node server"
},
"dependencies": {
"express": "~4.13.1",
"socket.io": "^1.4.6"
}
}
运行npm install
,
创建server.js - 粘贴在此处的原始代码:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
console.log(__dirname);
app.use(express.static(__dirname+'/public'));
app.get('/', function(req, res){
res.sendfile(__dirname+'/public/registration.html');
});
io.on('connection', function(socket){
socket.on('registration',function(msg){
console.log('user data'+ msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
在工作目录中创建/public
文件夹
创建/public/registration.html
文件:
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io('http://localhost:3000');
socket.on('connect', function() {
socket.emit('registration',"test");
document.getElementById('socket').innerHTML='connected';
});
</script>
</head>
<body>
<h1>Testing socket.io with nodejs</h1>
<h3 id="socket"></h3>
</body>
</html>
使用node server
或npm start
,
localhost:3000
它会起作用