i've got this error requests.
The red coloured Request getting Error - 400 Bad request and it taking more then 30sec .After the error the socket work fine but it taking more time for response
In app.js the code is follows
var app = express(),
server = require('http').createServer(app);
//io = require('socket.io').listen(server);
var sockets = require('socket.io')({
'transports': ['websocket', 'flashsocket','htmlfile','xhr-polling','jsonp-polling']
});
var io = sockets.listen(server,{ resource: '/socket.io/','sync disconnect on unload':true });
io.sockets.on('connection', function(socket){
socket.emit('server_emit');
socket.on('search', function(cattype,pagNo,lang,film,iteamcat,starname){
var query={'ProductType':cattype,'Language':lang,'ProductCategory':iteamcat,'UsedBy':starname,'UsedIn':film},
field={},
options={};
db.collection("Product").find(query,field,options).toArray(function(error, Product2){
socket.emit('result',Product2);
});
});
In client side code
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('server_emit', function(){
console.log("Server emitted to Browser")
});
</script>
Please help
Try specifying the full URL as
<script src='http://localhost:3000/socket.io/socket.io.js'>
and in socket var
= io.connect('http://localhost:3000/')
Related
I'm trying to create a socket in a client.js file to communicate with my server. I followed the official documentation ( https://socket.io/docs/#Using-with-Express ) with no success. Basically when I initialize my socket like this:
var socket = io();
i expect a message from my server (e.g. 'A user has connected') but nothing appear, letting me suppose that the connection never happens.
This is a project made on Glitch. I tried to follow socket.io documentation, simple examples or other questions tips. I both tried the suggested script before instantiate the socket and the cdn one.
//server.js
//dependencies
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
//listening to the port
http.listen(process.env.PORT || 3000, () => {
console.log("Listening on port " + process.env.PORT);
});
io.on('connection', function(socket){
console.log('A user has connected.');
});
//chat.html
//this is called right before </body>
<script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js'></script>
<script src='/socket.io/socket.io.js'></script>
<script src='/public/client.js'></script>
//client.js
var socket = io();
client.js is loaded as expected (and the console throws no errors) but i can't see 'A user has connected' as i'd expect.
You can check full source code here https://glitch.com/edit/#!/farlokko-advanced-node
Thanks.
UPDATE:
The problem was a wrong initialization of the passport.socketio module, which interfered with sicket.io . The main problem probably was a wrong store(memoryStore instead of mongo-store) and a wrong key for the cookie (express.sid instead of connect.sid).
Finally socket initialization was ok and had to be io.connect("host here").
As specified on the doc, you have to configure the client to connect to your localhost, and then, on the connection, you'll have your message :
<script>
var socket = io.connect('http://localhost'); // <--- HERE MAN
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
This function doesn't work in my app. I can't receive a message (socket.emit) from the server to the client (socket.on).
But i don't have this problem in the inverse (client to server).
I use cloud9 and the chat example from them works fine.
Here is my code for the server :
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
router.use(express.static(path.resolve(__dirname, 'client2')));
io.on('connection', function (socket) {
socket.emit('hello', 'i changed'); // !!!
});
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
and the code for the html page :
<html>
<head>
<title>test</title>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('hello', function (msg) { // !!!
document.innerHTML = msg;
});
</script>
</head>
<body>
<p>normal page</p>
</body>
</html>
And there is no change...
edit : with console.log either.
But the message seems sent with the socket :
Debugger listening on port 15454
info - socket.io started
Chat server listening at 0.0.0.0:8080
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized 13XpSYGuXzMpMeyFsRfO
debug - setting request GET /socket.io/1/websocket/13XpSYGuXzMpMeyFsRfO
debug - set heartbeat interval for client 13XpSYGuXzMpMeyFsRfO
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"hello","args":["i changed"]}
Can you help me please ?
You need to change
var socket = io.connect();
by
var socket = io.connect('http://0.0.0.0:8080');
var socket = io.connect() <- this should specify the domain to which you are connecting.
So i did alot in this, trying to get it to work, it sorta did but i don't work like you do, i'm a beginner and not compatible with how you code but i've figured out that the problem is the port the io is using
var io = socketio.listen(server);
or where the html is getting the connection
<script src="/socket.io/socket.io.js"></script>
to me, the html is requesting a js file in it's own dir, but it shouldn't.
When i use socket.io, i put this in the server
var client = require("socket.io").listen(8080).sockets
The main part is the listen, it listens on the port 8080 and in my html i do
var socket = io.connect("http://127.0.0.1:8080");
Which works, i'm sorry for this, i am mostly sure this isn't an answer but i've tried, i hope you get it done, even if a year and 3 months have passed.
$(function(){
var socket = io();
socket.on('hello',function(data){
$('#lblmsg').text(data.message);
});
});
this is something I am working with. in the 4th line of my code, data is passed and data.message is retrieved. but you directly equated msg with the innerhtml, on the html page(in the block you commented \!!!)
see if you are still working on it!
i am using node.js and socket.io for the real time notification system, so i have tested node.js and socket.io with simple chat code, it pretty good with localhost but can't access the same from the another system which are connected locally with same network, my server and client code looks like below
server.js
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(8888);
and client html index.html
<script src="http://localhost:8888/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('http://localhost:8888');
</script>
it's working on my browser with this url http://localhost/schat/index.html but not working when i'm trying connect from another one system using my ip 192.171.56.23/schat/index.html but all other html files working fine, below is my netstat output
[root#localhost schat]# netstat -pan | grep 8888
tcp 0 0 0.0.0.0:8888 0.0.0.0:* LISTEN 8068/node
tcp 0 0 127.0.0.1:8888 127.0.0.1:38273 ESTABLISHED 8068/node
tcp 0 0 127.0.0.1:38273 127.0.0.1:8888 ESTABLISHED 7990/firefox
Here is a working example from socket.io docs (slightly modified).
use <script src="/socket.io/socket.io.js"></script>
instead of <script src="http://localhost:8888/socket.io/socket.io.js"></script>
and use var socket = io.connect(window.location.origin);
instead of var socket = io.connect('http://localhost:8888');
(socket.io v1.3.5, express v4.12.2)
index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(window.location.origin);
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
server.js
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8888);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Change your client side code to
<script>
var url = window.location.host;
var socket = io.connect(url);
</script>
I had the same problem and I fixed it :
First you have to change http://localhost:8888/ to http://your_IP_address:8888/ everywhere in your code.
Second, which took me too much time to fix was to change server.listen(8888); to server.listen(8888, "your IP address");
Thank Karim, your solution work for me, in the 'server.js' configuration I set the 'port' value and the 'server', but not the ip, I use only the name without 'https://', like this:
// External route.
var express = require("express");
var router = express.Router();
// In cloud 9 use port 8081
const port = 8081;
const webLnk = 'mywebdevaddress.io';
// In dev local ambient 'localhost' work without the 'port' and the server, in prod internet // you need to specify the port and the link name.
const server = require('http').Server(router).listen(port, webLnk);
const io = require('socket.io')(server);
Is the official socket.io docs I do not see any of this!
I'm using node.js and socket.io for a simple app. My browser is receiving data from server nicely but server not receiving from client(browser). May be the event listener for client_data not working. Here is the server:
var http = require("http");
var url = require("url");
var io = require('socket.io');
function start(route) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(pathname, response);
}
var server = http.createServer(onRequest);
server.listen(8888);
var server_io = io.listen(server);
server_io.on('connection', function(socket){
//send data to client
setInterval(function(){
socket.emit('date', {'date': new Date()});
}, 1000);
});
//recieve client data
server_io.on('client_data', function(data){ //May be it is not listening
process.stdout.write(data.letter); // not working
//console.log(data.letter); not working
});
console.log("Server has started.");
}
exports.start = start;
Client code:
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
var socket = io.connect();
socket.on('date', function(data){
document.getElementById("date").innerHTML = data.date;
});
function sendKey(e){
socket.emit('client_data', {'letter': String.fromCharCode(e.charCode)});
}
</script>
<div id="date">This is our socket.html file</div>
<textarea id="text" onKeyPress="sendKey(event)"></textarea>
</body>
</html>
What is the problem with my server code?
This error occurs because .on('client_data') must be binded to socket, not server_io. The code may look like the following:
server_io.on('connection', function(socket){
setInterval(function(){
socket.emit('date', {'date': new Date()});
}, 1000);
socket.on('client_data', function(data){
process.stdout.write(data.letter);
});
});
server_io only recieves connection events. The client_data event sent from the client is heard by the socket object passed into the connection callback, not the server_io object.
You need to use socket.on("client_data", ...); and move that code into your connection callback.
That socket object is connected to a particular client web page instance, and it recieves messages only sent by that page. Each time a new client page connects, a new socket object is created and passed as an argument into the connection handler function.
hey i just started tinkering with node.js and am a complete noob. i am trying to get a simple client server communication going using socket.io and express (i have never used these before).
here is my code for the app(app.js):
var sys = require('sys'),
express = require('express'),
app = express('localhost');
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000);
var socket = require('socket.io').listen(server);
socket.on('connection', function (client){
// new client is here!
setTimeout(function () {
client.send('Waited two seconds!');
}, 2000);
client.on('message', function () {
}) ;
client.on('disconnect', function () {
});
});
and here is my code for the client(client.html):
<html>
<p id="text">socket.io</p>
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
var socket = new io.Socket(),
text = $('#text');
socket.connect();
socket.on('connect', function () {
text.html('connected');
});
socket.on('message', function (msg) {
text.html(msg);
});
socket.on('disconnect', function () {
text.html('disconnected');
});
});
</script>
i got most of the code from:
NodeJS + socket.io: simple Client/Server example not working
and the changed it to be compatible with express 3.x
however when i run the server and open my client using chrome it tells me that it is unable
to load resource file:///socket.io/socket.io.js
i have already installed express and socket.io using npm
also i have read through atleast 20 similar posts and have not been able to find an answer
please help me. thank you
socket.io.js file needs to be served from port 3000, like localhost:3000.
So here is what you do change
<script src="/socket.io/socket.io.js"></script> to
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
Are you opening the client.html page directly from the local file system? The request for socket.io.js should look like http://localhost/socket.io/socket.io.js not file:///socket.io/socket.io.js.