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.
Related
I am trying to create socket connection using node js express and socket.io in my project folder which is on Linux(Ubuntu) server. After installing nodejs, npm, socketio and express I am unable to create socket connection. Tried to run node app.js but no output comes. Installation is done following the tutorial http://www.programwitherik.com/getting-started-with-socket-io-node-js-and-express/. I am including code for app.js and index.html
//app.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
});
app.use(express.static(__dirname + '/node_modules'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(8000);
//index.html
<!doctype html>
<html lang="en">
<head>
<script src="http://example.abcd.net/socket-app/jquery/dist/jquery.js"></script>
<script src="http://example.abcd.net:8000/socket.io/socket.io.js"></script>
</head>
<body>
<h1>Hello World!</h1>
<div id="future"></div>
<form id="form" id="chat_form">
<input id="chat_input" type="text">
<input type="submit" value="Send">
</form>
</body>
</html>
<script>
var socket = io.connect();
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
</script>
example.abcd.net is the sample address in which socket-app is the folder which contains app.js and index.html file. Also how to run it on browser as every tutorial runs it using localhost. Similar code works fine when installed on local machine.
Try using io.connect("http://example.abcd.net:8000"); instead of io.connect();
I have a basic node express/socket example app from the socket.io official website (linked pasted below) and i noticed that when a user connected, the 'connection' even just kept firing over and over again.
So i found a post (Socket IO chat repeating user connected) saying that there is a bug in socket.io 2.x.x and when i reverted to socket.io 1.3.7 this issue did stop, is this a confirmed bug, and we should roll back to a 1.x.x version? Or is there a new way of using socket.io that doesn't reflect on the current documentation?
My server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
My Client side code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
My server terminal output (which just repeats forever):
a user connected
a user connected
a user connected
...
Socket.io official example:
https://socket.io/get-started/chat/
Since socket.io released version 2.x, there appears to be an issue that causes an infinitely recurring connect, disconnect, connect, disconnect and so on forever if you have mismatched versions of socket.io code on client and server.
This can be further exacerbated by client-side caching which can get the browser client stuck on an older version sometimes.
The usual fix is to make sure you're getting the socket.io client with /socket.io/socket.io.js because then the socket.io server sends the client version that matches it exactly. But, you appear to already being doing that, so I'd guess that you have some sort of browser caching problem. You can clear the browser cache manually to see if this is the issue.
Use this for the server:
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('node_modules')); // serve static files
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
And this in the HTML:
<!DOCTYPE html>
<html lang="en">
<body>
<script src="socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
The bug might be with the <script src="/socket.io/socket.io.js"></script> tag that Socket IO provides.
I'm having trouble connecting to socket.io. With the code below, I keep getting an 'io is not defined' error on my browser console. Anyone have any idea what I'm doing wrong here? I've been poking around stackoverflow for hours, but no solution seems to work...
server side:
,db = require("../../lib/db")
,config = require("../../config")
,app = require("../index")
,io = require('socket.io')(app);
;
io.on('connection', function (socket) {
console.log('connected')
});
exports.render = function(req, res){
console.log(io)
res.render("vitron", {});
}
client side:
<!doctype html>
<html>
<head>
<title>Sockets</title>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</head>
<body>
</body>
</html>
You apparently don't have the right server-side initialization so that your server will automatically serve the /socket.io/socket.io.js file.
There are many ways to do this, but the simplest way that is documented in the socket.io documentation is to use some built-in middleware that will have the socket.io server-side library automatically intercept the request for the /socket.io/socket.io.js file and serve up the script file.
The socket.io documentation shows exactly how to do this when using express with node. If you aren't using express, then you can do it with your own middleware. Or, if you're just using plain node, you will have to either handle that route yourself or just put the /socket.io/socket.io.js file in a known location that it can be requested directly from. You can even link to it on a CDN if you want, but there is an advantage to using the built-in scheme because when/if you upgrade the socket.io library on the server, it will automatically contain a matching client-side library which is kind of nice.
I don't know exactly what your overall setup is, but here's my socket.io initialization with express 4.
var express = require('express');
var app = express();
var server = app.listen(8081, function() {
console.log(new Date().toISOString() + ": server started on port 8081");
});
var io = require('socket.io').listen(server);
I'm not able to get socket.io working on my machine with one of the very basic socket.io chat examples (just the preliminary test of it) by Guillermo Rauch locally and on cloud9 platform. I've tried socket.io in combination with both express 2.5.x and express 3 (changing the server code accordingly) and get the same behaviour using both Nodeclipse and command line running:
info: socket.io started
Socket server running # localhost on port
3000
When I visit localhost:3000 I get :
debug: served static content /socket.io
There is no handshake and perhaps the client is not connecting.
Maybe the problem is easy to see but I couldn't find an answer suiting my case here and elsewhere. Here is my environment:
Windows 7 x86 or Windows 8 64bit;
Nodeclipse upon latest stable Node (0.10.15 if I'm not mistaken);
used: google chrome, firefox, IE up to date;
tried also to serve the index page via WAMP server;
tried a lot of alternatives, which seems to suggest it is not a problem of code but belonging to something else (express not working well with the latest node installs? something wrong about environment variables?);
express seems to serve the /socket.io/socket.io.js file since it is readable through any browser when I enter localhost:3000/socket.io/socket.io.js (I don't know if this is the right test).
Here is the client code:
<!doctype html>
<html>
<head>
<title>my test</title>
<script src="/socket.io/socket.io.js"></script>
<script src="chat.js">
<link href="/stylesheets/style.css" rel="stylesheet" />
</head>
<body>
<div id="chat">
<ul id="messages"></ul>
<form id="form">
<input type="text" id="input" />
<button>Send</button>
</form>
</div>
</body>
</html>
Here is the serverside app:
var express = require('express');
var sio = require('socket.io');
var app = express.createServer(
express.bodyParser(),
express.static('public'));
app.listen(3000);
var io = sio.listen(app);
console.log('Socket server running # localhost on port ' + 3000);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log('hello');
});
});
chat.js contains:
window.onload = function() {
var socket = io.connect("http://localhost:3000");
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
};
these are the versions of socket.io and express, installed locally (express is also installed globally) via npm install command given from the nodeclipse workspace folder (c:/users/myname/workspace/nameoftheapp)
"express": "2.5.4",
"socket.io": "0.9.16"
Structure of the project
node_modules
|- [...] (all the installed folders and files]
public
|- stylesheets
--|-style.css
|- index.html
app.js
package.json
readme.md
Do I have to set something in the connection to point to my workspace correctly?
You need to use http.createServer instead of express.createServer
var express = require("express");
var http = require("http");
var app = express();
var server = http.createServer(app);
var io = require("socket.io").listen(server);
server.listen(3000, function () {
console.log("listening on port 3000");
});
I came across this question while trying to figure out how to use socket.io on Cloud9. I don't know how Cloud9 factors into your question (it's mentioned in your title though), but for me I was not able to establish the handshake from the client, and only got a debug: served static content message in the Cloud9 terminal. I eventually figured out it was the connection link in the client that was causing the problem. Setting up Express with socket.io wasn't easy either as you can get confused between the different variables like what Peter said.
Server Code:
var express = require('express'),
http = require("http"),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
server.listen(process.env.PORT || 3000, function() {
console.log('Express server started on port %s', process.env.PORT);
});
io.sockets.on('connection', function(socket) {
socket.emit('news', {
hello: 'world'
});
socket.on('my other event', function(data) {
console.log(data);
});
});
Client Code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(window.location.hostname);
socket.on('news', function(data) {
console.log(data);
socket.emit('my other event', {
my: 'data'
});
});
</script>
I used window.location.hostname so that the script would work both on the Cloud9 test server and wherever I deploy my app (Heroku in my case).
Used with Express 3.2.6 and Socket.io 0.9.13.
today I follow an tutorial by Gonzalo Ayuso at http://gonzalo123.com/2011/05/23/real-time-notifications-part-ii-now-with-node-js-and-socket-io/ but it can't send the message
Here is my server.js
var http = require('http');
var io = require('socket.io');
server = http.createServer(function(req, res){
});
server.listen(8000);
//socket.io
var socket = io.listen(server);
socket.set('transports', ['websocket']);
console.log("Start");
socket.on('connection', function(client){
client.on('message', function(msg){
console.log(msg);
socket.broadcast(msg);
})
});
and the client.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Comet Test</title>
</head>
<body>
<p><a id='customAlert' href="#" onclick='socket.send("customAlert")'>publish customAlert</a></p>
<p><a id='customAlert2' href="#" onclick='socket.send("customAlert2")'>publish customAlert2</a></p>
<script src="http://localhost:8000/socket.io/socket.io.js" type="text/javascript"></script>
<script type="text/javascript">
// Start the socket
var socket = io.connect('http://localhost:8000');
socket.on('message', function(msg){
console.log(msg);
});
</script>
</body>
</html>
I have edited it just a little bit to run on my server. But the client doesn't send message to server. Can anybody help me? Sorry for my bad English.
I have found out that the client can't connect to server but I don't know why?
My computer is running xampp with apache server. Maybe it's problem?
Updated:
I have just set transports to xhr-polling and it connect success. Why doesn't it accept websocket?
you need to read more carefully the tutorials about socket.io
first of all to call some event, you need to emit the event name:
socket.emit('my other event', { my: 'data' });
thats mean, on your onclick in anchor need to call socket.emit ..., or to call some function like:
function call_my_event(name){
socket.emit(name,{my : 'data'});
}
I have found out my problem. It's about firewall or proxy or something else in my computer block websocket protocol. I tested that code on another computer and it works fine. So I have to re-install my system and websocket is available for me :D