Bula
Bula

Reputation: 2792

Node JS communicating through sockets

I'm trying to play around with sockets. I created a web server in node:

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");
    });


 });

I also have a html file:

 <!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>

What I'm trying to achieve is when I press that button my console logs "someone clicked the button". However at the moment nothing happens. I'm not sure what I'm missing

UPDATE As @Zub recommended I added

console.log("clicked");

right before the socket.emit(); I checked the console and this is the output:

    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 

Upvotes: 0

Views: 244

Answers (2)

Oleg
Oleg

Reputation: 23337

Since you bind node server on 1337, you have to point that port when you load socket.io.js script.

So try to replace

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

with

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

Edit

You should also initialize client socket.io connection beyond clickedButton function and leave just socket.emit("input_written"); in it.

Upvotes: 1

eww
eww

Reputation: 586

The url in your browser needs to match the socket connection url. You have localhost in your io.connect, so make sure the url in your browser reads http://localhost/. If you connect to http://127.0.0.1/ in your browser then it won't work.

Upvotes: 0

Related Questions