我试图与套接字玩耍。我在节点创建的Web服务器:节点JS通过套接字进行通信
var http = require("http");
var server = http.createServer(function(req,res){
console.log("server has been created");
res.writeHead(200,{"Content-type:": "text/plain"});
res.end("Welcome to my supa' nodejs app");
}).listen(1337);
console.log("Server running at 127.0.0.1:1337");
var io = require("socket.io").listen(server);
io.sockets.on("connection", function(socket){
socket.on("input_written",function(){
console.log("someone clicked the button");
});
});
我也有一个html文件:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html lang="en">
<head>
<title>Home page</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://localhost:1337");
function clickedButton()
{
socket.on("connect",function(){
socket.emit("input_written");
});
}
</script>
<button type="button" onclick="clickedButton()">Click me</button>
</body>
</html>
我试图实现当我按下该按钮,我的控制台登录“,用户点击该按钮”。但目前没有任何反应。我不知道我错过了什么
UPDATE 作为@Zub推荐我的socket.emit之前添加
console.log("clicked");
(); 我检查控制台,这是输出:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined (index):11
Uncaught TypeError: Cannot call method 'on' of undefined
我建议初始化客户端io连接超出'clickedButton'函数,因为您肯定不想在每个按钮单击上建立新的连接。还要在'socket.emit(“input_written”);'之前写'console.log('clicked');''。点击按钮时浏览器控制台输出是否“点击”? – Curious
@Zub检查更新 – Bula
您应该删除'socket.on(“connect”...''表单,并且只保留'socket.emit(“input_written”);'否则它不会起作用 – Curious