There are other posts asking the same question but my situation is different. The code works but with the error "failed: Connection closed before receiving a handshake response" displayed in Chrome console. I tried to strip all the code and came up with a very slimmed down code which continues to give the error. Here is the test case:
Server side:
var http = require('http');
var express = require('express');
app = express();
server = http.createServer(app);
serveFile = function (req,res) {
res.sendFile(__dirname + '/socket.html');
};
io = require('socket.io')(server);
io.sockets.on('connection',function(socket) {
socket.on('from_client',function(data) { console.log(data.name); });
socket.emit('dateFromServer', {'date': new Date()});
});
app.use(serveFile);
io.listen(server);
server.listen(2000);
Client side: (the socket.html file)
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
</head>
<body>
<script>
var socket = io.connect();
socket.on('dateFromServer', function(data){
$('#date').text(data.date);
});
socket.emit('from_client',{'name':'John'});
</script>
<div id="date">Date will be displayed here</div>
</body>
</html>
~
Please, can someone explain what is causing the error? The messages are sent/received, from the client/server, as expected.
~
Related
I can't solve this error of socket.io it shows in the console
GET /socket.io/socket.io.js net::ERR_ABORTED 404
Refused to execute script from '/socket.io/socket.io.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Uncaught ReferenceError: io is not defined
at script.js:1:14
I made this with node.js
The files are below (main server file is index.js)
index.js
var express = require("express");
var app = express();
var http = require("http");
var server = http.createServer(app);
var { Server } = require("socket.io");
var io = new Server(server);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("/style.css", (req, res) => {
res.sendFile(__dirname + "/style.css");
});
app.get("/script.js", (req, res) => {
res.sendFile(__dirname + "/script.js");
});
io.on("connection", (socket) => {
socket.on("chat message", (msg) => {
io.emit("chat message", msg);
});
});
app.listen(3000);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Test Socket.io</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center>
<h1>Test</h1>
</center>
<script src="/socket.io/socket.io.js"></script>
<script src="script.js"></script>
</body>
</html>
style.css
body {
font-family: Arial;
}
script.js
var socket = io();
Help will be appreciated.
Replace this:
app.listen(3000);
with this:
server.listen(3000);
app.listen() creates a new server so the server you're starting is NOT the server that socket.io is hooked to, therefore the socket.io library is not hooked up to that server and when the request for /socket.io/socket.io.js comes in, you don't get the socket.io JS library.
Here's the code for app.listen():
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
You can see that it creates a new server and then calls .listen() on that new server.
Your express code works because app is hooked to the server created by app.listen(), but socket.io is hooked to the server created by:
var server = http.createServer(app);
var io = new Server(server);
which is never started and is not running. So, socket.io is never hooked up to the server that is actually running. Instead, you should just create and start one server and hook both app and socket.io to that one server.
I am trying to develop a live chat application using laravel. I face a problem. When I run "node index.js" , 'A connection has made' message has shown continuously in command prompt.
my index.js file is:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
app.get('/', function(request, response){
response.sendFile(__dirname+ '/index.html');
});
io.on('connection', function(socket){
console.log('A connection has made');
// socket.on('chat.message', function(message){
// io.emit('chat.message', message);
// });
});
My index.html page is:
<!DOCTYPE html>
<html>
<head>
<title>Live Chat</title>
</head>
<body>
<div class="container" id="chat">
<h1> Chat System </h1>
</div>
<script type="text/javascript">
var socket = io();
</script>
</body>
</html>
How can I solve it?
The usual reason that your client is continually trying to connect over and over again is because you have a mismatched client and server version of socket.io making them incompatible. You don't show how you load the socket.io Javascript in your web page, but if you do it like this:
<script src="/socket.io/socket.io.js"></script>
Then, you will always get the version that exactly matches your server from your server automatically (this is a route that the socket.io server automatically adds to your Express server).
If you are loading socket.io from a CDN, then you have to either switch to the above to load it from your own server or manually specify the exact same version from the CDN as you are running on the server.
If you are using it on React/NextJs
just declare these as global
import socketClient from "socket.io-client";
const SERVER = "http://127.0.0.1:8000";
const socket = socketClient(SERVER);
export default chatApplication=()=>{
//main component
}
Change port number from 3000 to 7000 for example.
I have a problem with socket.io
when I refresh the client page, sockets are increased.
for example, this is the sample code
var express = require("express"),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.get("/",(req,res)=>{
var doc=`
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
</script>
</head>
<body>
<h1>hello!</h1>
</body>
</html>
`
res.send(doc);
io.on("connection",function(socket){
console.log("connected!")
})
})
on the first connection, server log has 1 "connected!" message.
and refreshing the client page, the console.log() fired double. so log has 3 "connected!" messages
refreshing one more it fires triple -> 6 connected messages
and next quadriple!
I don't know why connections are multiplexed. could you help me?
Your event handler for the server-side socket you declared needs to be registered just once.
var express = require("express"),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
io.on("connection",function(socket){
console.log("connected!")
})
app.get("/",(req,res)=>{
var doc=`
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
</script>
</head>
<body>
<h1>hello!</h1>
</body>
</html>
`
res.send(doc);
})
Every time a request comes in from the browser, you were adding a new anonymous function as an event listener to any socket opened.
I uploaded a server-side code to AWS Amazon EC2 with node.js and socket.io.
When I connect to that server from browser(both on desktop and ios safari), it works with no problem.
But, when I create a cordova project and modify some of the codes to comply with cordova, get it run on ios device, it doesn't work!
I tried
<access origin="My-server-side-url-comes-here*"/>
but it didn't solve the problem.
Also, i opened up port :9000 on EC2 for TCP connection.
It seems that socket = io.connect(serverUrl); is causing problem..
I've been struggling to get this work for days now...
Can anyone tell me how to get socket.io work with external host, phonegap, and ios?
server side code uploaded to AWS Amazon EC2 (app.js)
var http = require('http');
var socketio = require('socket.io');
var server = http.createServer(function (request, response){
console.log('server created');
}).listen(9000, function(){
console.log('server running!');
});
var io = socketio.listen(server);
io.sockets.on('connection', function(socket){
socket.on('msg', function(data){
console.log(data);
io.sockets.emit('msg_by_server', "server got your msg:"+data);
});
});
client-side code that works with desktop browsers and iPhone safari(which works fine) (index.html)
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script>
var socket;
var serverUrl = "sampleURL.compute.amazonaws.com:9000";
window.onload = function(){
socket = io.connect(serverUrl);
socket.on('msg_by_server', function(data){
alert(data);
});
}
var sendMessage = function(){
socket.emit('msg', 'msg from client');
}
</script>
</head>
<body>
<button onclick = 'sendMessage();'>Message Send</button>
</body>
</html>
different client-side code used for phonegap(which doesn't work) (index.html)
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
alert('check1');
var socket="";
app.initialize();
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert('check2'); // shows up
var serverUrl = "sameURL.compute.amazonaws.com:9000";
socket =io.connect(serverUrl);
alert('check3'); // doesn't show up
socket.on('connect', function(){
socket.on('msg_by_server', function(data){
alert(data);
});
socket.emit('msg', 'msg from client')
});
}
var sendMessage = function(){
alert(socket);
socket.emit('msg', 'msg from client');
};
</script>
</head>
<body onload="onDeviceReady();">
<!--
i put onload="onDeviceReady();" because
document.addEventListener("deviceready", onDeviceReady, false);
doesn't seem to work for some reason..
-->
<button onclick = 'sendMessage();'>amessageSend</button>
</body>
</html>
I’m having a problem getting started with Node.js.
I’ve created a basic server that I know works, because if I navigate to http://localhost:5000 in my browser I get the expected message. However, I’m having trouble then connecting to this server on the client side with a basic HTML page.
My Node.js app looks like this:
var http = require('http');
var socket = require('socket.io');
var port = process.env.PORT || 5000;
var players;
var app = http.createServer(function(request, response) {
response.write('Server listening to port: ' + port);
response.end();
}).listen(port);
var io = socket.listen(app);
function init() {
io.configure(function() {
io.set('transports', [ 'xhr-polling' ]);
io.set('polling duration', 10);
});
io.sockets.on('connection', onSocketConnection);
};
function onSocketConnection(client) {
console.log('New connection');
console.log(client);
};
init();
My HTML page looks like this (based on https://github.com/mongolab/tractorpush-server/blob/master/index.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/');
socket.on('all', function(data) {
console.log(data);
});
socket.on('complex', function(data) {
console.log(data);
});
</script>
</body>
</html>
I understand that the sockets.io.js file is automatically generated by socket.io, but I just get the following error when I view my index.html file:
Uncaught ReferenceError: io is not defined
How do I actually connect to my server?