我目前正在尝试使用socket.IO。 但是由于某种原因,我没有收到来自客户的发射。 我正在使用Node.js并表示要托管html文件。
这是我当前的代码: server.js
var express = require('express');
var app = express();
var path = require('path');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var d = new Date();
var temp = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
app.get('/', function(req, res){
//res.sendFile(__dirname + '/public/index.html');
app.use(express.static('public'));
});
io.on('connection', function(socket){
console.log(temp + ' :A User connected');
console.log('Socket ID: ' + socket.id);
socket.on('disconnect', function(){
console.log(temp +' :A User disconnected');
console.log('Socket ID: ' + socket.id);
socket.on('testCon', function(){
console.log('Received');
});
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sockets Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script type="text/javascript" src="./js/client.js"></script>
</head>
<body>
<p>Socket Test Site</p>
<button onclick="newConnection();">Connect</button>
<button onclick="myFunction();">Execute</button>
</body>
</html>
client.js
var socket;
function newConnection() {
socket = io();
}
function myFunction() {
socket.emit('testCon', null);
console.log("Button Pressed");
}
我不确定现在是什么问题。
谢谢!