2014-02-17 57 views
0

我试图与套接字玩耍。我在节点创建的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 
+0

我建议初始化客户端io连接超出'clickedButton'函数,因为您肯定不想在每个按钮单击上建立新的连接。还要在'socket.emit(“input_written”);'之前写'console.log('clicked');''。点击按钮时浏览器控制台输出是否“点击”? – Curious

+0

@Zub检查更新 – Bula

+0

您应该删除'socket.on(“connect”...''表单,并且只保留'socket.emit(“input_written”);'否则它不会起作用 – Curious

回答

1

由于您在1337上绑定节点服务器,因此在加载socket.io.js脚本时必须指向该端口。

所以尽量用

<script src="http://localhost:1337/socket.io/socket.io.js"></script> 

编辑

你也应该初始化客户端socket.io超越clickedButton功能连接,并在它离开只是socket.emit("input_written");更换

<script src="/socket.io/socket.io.js"></script> 

0

在浏览器的网址需要与插座连接的URL。你的io.connect中有localhost,所以请确保浏览器中的url为http://localhost/。如果您在浏览器中连接到http://127.0.0.1/,那么它将不起作用。

+0

我的浏览器指向本地主机,它不会记录“按钮点击” – Bula

相关问题