Binit Ghetiya
Binit Ghetiya

Reputation: 1979

Socket Failed to load resource server (404 error)

hey guys m using to files for server side server.js and at client side using javascript

server.js

var express = require("express");
var io = require("socket.io").listen(app);
var app = express.createServer("localhost");
app.listen(3000);


app.get('/', function (req, res) {
    res.sendfile(__dirname + '/hello.html');
});

    console.log("before");
    io.sockets.on("connection", function (socket) {
        console.log("after");
        socket.on("message send", function (data) {
            io.sockets.emit("new mesage", data);
        });
    });

and at client side using one html page name

hello.html

<html>
<head>
    <style>
        #chat{
        height : 500px;
        }

    </style>

</head>
<body>
    <div id="chat" > </div>
    <form id ="send message"> 
        <input id="message" type="text" ></input>
        <input type="submit"></input>
    </form>
    <script type= "javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>

    <script>
    jQuery(function($){
        var socket =io.connect();
        var $messageForm = $("#send message");
        var $messageBox=$("#message");
        var $chat = $("#chat");

            $messageForm.submit(function(e){
                e.preventDefault();
                socket.emit("message send" , $messageBox.val());
            });
            socket.on("new message", function(data){
                $chat.append(data + "</br>");   
            });
    });
    </script>

</body>
</html>

when m start server then its proporly working but when i sent a request then it shows error like given blow

Failed to load resource: the server responded with a status of 404 (Not Found) /socket.io/socket.io.js

Uncaught ReferenceError: jQuery is not defined

versions

socket.io:0.9.16

exparess:3.4.0

thanks for your time :)

Upvotes: 0

Views: 8048

Answers (1)

Sriharsha
Sriharsha

Reputation: 2443

You need to bind the socket.io to the http server not the application server. Changes this to below..

var express = require('express'),
    app = express(),
    http = require('http'),
    server = http.createServer(app),
    io = require('socket.io').listen(server);

Refer Express guide for more info.

EDIT

To correct the Jquery error..

replace

jQuery(function($){

with

$(document).ready(function($)

Upvotes: 3

Related Questions