I have the following app with express/socket.io (the app is listening and live without any errors).
When I http-request it I get the following error:
GET http://xxxxxxx.com:3035/socket.io/1/?t=1449090610579 400 (Bad Request)
And on the socket.io reponse at http://xxxxxxx.com:3035/socket.io I get:
Cannot GET /socket.io
app.js:
var express = require('express'),
http = require('http'),
sio= require('socket.io'),
fs=require('fs'),
app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'xxxxxxx',
password: 'xxxxxxx',
database: 'xxxxxxxxx'
}
);
connection.connect();
// Start the server
var server=app.listen(3035, function () {
console.log("Express server listening on port %d",3035);
});
app.io=io=sio.listen(server);
.
.
.
on the client side:
var socket = io.connect('http://xxxxxx.com:3035');
Your sio is a function. You need to call it with your server as an argument.
Add
server=require('http').Server(app)
sio=require('socket.io')(server)
io.connect() takes a URL such as http://example.com:3035.
You are passing xxxxxx.com:3035 which is not a proper URL form.
Also, note that if you're just trying to connect to the same server and port as the web page came from, you can just use:
io()
or
io.connect()
And the socket.io library will connect back to the same host and port as the web page.
You should initialize default connection on client side by
io.connect( "/" );
According to documentation by default socket.io will connect to the same host and port where rendered webpage is. The / in the path states to connect to default namespace.
Related
I can set the port on the Web socket server as shown below.
const wss = new WebSocketServer({
port: rrPort,
});
(I tried set with 'host' and 'path' but it doesn't work.)
Now I have to set specific ip on the Web socket server.
I have two LAN so also IPs.
I wanna set with one of IPs but I can't.
I can get web socket server ip with connected PC as shown below.
const ip = ws._socket.remoteAddress.slice(7);
You need to set the ip when you create http server which you pass to WebSocketServer to use.
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(...);
// this is where you set the ip to listen to
server.listen(8080, '192.168.0.1', function() {
});
wsServer = new WebSocketServer({
httpServer: server,
port: 1234
});
I'm having trouble with being able to connect to my node.js server from an external domain. It works fine when running it locally using the http web server through node however when connecting externally, it loads the socket.io.js file just fine but when trying to use the socket it removes the port from the URL and cannot connect.
Instead of doing this in the network requests:
http://external-domain.com:3000/socket.io/?EIO=3&transport=polling&t=M06GOUU
it does this:
http://external-domain.com/socket.io/?EIO=3&transport=polling&t=M06GOUU
I'm not sure how to make it not remove the port from the connection. How do I go about fixing this?
SERVER
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const publicPath = path.join(__dirname, '../public');
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
app.use(express.static(publicPath));
server.listen(3000, () => {
console.log(`Server is up on port 3000`);
});
CLIENT SCRIPT TAG
<script src="http://external-domain.com:3000/socket.io/socket.io.js"></script>
CLIENT JS ON A DIFFERENT DOMAIN
var socket = io();
socket.connect('http://external-domain.com:3000');
socket.on('connect', function () {
console.log('Connected to server.');
});
Change from this:
var socket = io();
socket.connect('http://external-domain.com:3000');
to just this:
var socket = io("http://external-domain.com:3000");
And, you don't use the socket.connect() as you will already have requested the connection with the io("http://external-domain.com:3000"); call.
Explanation
The code:
var socket = io();
uses the page URL to connect to a socket.io server at that origin. That is not what you want (apparently).
If you wanted to use the .connect() method, it would be like this:
var socket = io.connect("http://external-domain.com:3000");
Note: var socket = io(url) is simply a shortcut for var socket = io.connect(url).
socket.connect() does not accept a URL as a parameter so you simply weren't using that correctly. It's just a synonym for socket.open().
Use io.connect("url")
var socket = io.connect("http://external-domain.com:3000", { rejectUnauthorized: false });
// { rejectUnauthorized: false } is an optional parameter.
Hope this works for you.
Here is the problem. When I load the page in the browser and check to see if my "test" was emitted, I run into this wall of spamming polling.
The code I use is exactly the same as in other projects I have done, so it makes no sense to me that this doesn't work now. -_-
app.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8000;
server.listen(port, function(){
console.log('server ready - listening on *:8000');
});
app.get( '/*' , function( req, res, next ) {
//This is the current file they have requested
var file = req.params[0];
//Send the requesting client the file.
res.sendFile( __dirname + '/' + file );
});
io.on('connection', function (socket) {
socket.on('test', function(){
console.log("test worked");
});
});
client.js
var socket = io();
socket.emit("test");
I broke the code down to what you see above. There's nothing else. And it doesn't work. internal screaming
I'll post my comment as an answer so you can wrap up this question. One common reason that socket.io will loop with http requests and never successfully connect is if you are running mismatched version on the client and server. This seems to have happened recently with socket.io upon a recent version change so they must have made some change in how the connection logic works that makes it fail to connect if versions are mismatched.
If you load your client via this:
<script src="/socket.io/socket.io.js"></script>
Then, the client will always match the server version as long as you don't have any other <script> tags that are loading some other version of socket.io.
One more solution which worked for me ( Socket.IO 2.3.0 and Socket.IO Client 2.3.0 ) is to set the transports field when you create the instance of io on back-end and socket on front-end , like this :
On back-end :
io = require('socket.io')(http,{
log: false,
agent: false,
origins : '*:*' , // this is for the CORS browser error , I also use the cors npm module here
transports : [ 'websocket' ]
});
And on front-end :
const socket = socketIOClient(url,{
forceNew : false ,
secure : true ,
transports: [ 'websocket' ]
});
Hope it helps , if not the question owner , then maybe the others :)
I'm trying to have a websocket server on a subdomain so the client would point to something like 'ws://ws.mydomain.com'.
I'm using the subdomain module to handle normal get requests to subdomains but not sure how to consolidate the two. Any ideas on how I can approach this?
The WebSocketServer can take a server object, but can't figure it out.
var WebSocketServer = require('ws').Server
var express = require('express');
var subdomain = require('subdomain');
var app = express();
var wss = new WebSocketServer({port: 8081, server: http.Server});
app.use(subdomain({ base: 'mydomain.com', removeWWW: true}));
wss.on('connection', function(ws){
console.log('a connection!');
});
app.get('/subdomain/unrelatedsub', function(req, res){
res.send("hello unrelated subdomain page");
});
app.listen(80);
Link to WS documentation
From the web socket protocol:
The WebSocket Protocol attempts to address the goals of existing
bidirectional HTTP technologies in the context of the existing HTTP
infrastructure; as such, it is designed to work over HTTP ports 80
and 443 as well as to support HTTP proxies and intermediaries, even
if this implies some complexity specific to the current
environment.
Express 3 exposes the app as a request handler, you must instantiate a http.Server first which you can pass the express app into, and then you setup your sockets, as the ws:// protocal can share the HTTP port you listen on, just as wss:// would share the HTTPS port.
Try something closer to this, I will test when get a chance if you haven't responded:
var WebSocketServer = require('ws').Server
var express = require('express');
var http = require('http')
var app = express();
app.use(subdomain({ base: 'mydomain.com', removeWWW: true}));
var server = http.createServer(app);
server.listen(8080);
var wss = new WebSocketServer({server: server});
wss.on('connection', function(ws){
console.log('a connection!');
});
app.get('/subdomain/unrelatedsub', function(req, res){
res.send("hello unrelated subdomain page");
});
How to do socket.io implementation in Webrtc Video calling?
A little bit overload but it works: SocialVidRTC
I understand from your question that you already have a WebRTC project and some signalling mechanism in server.js , possibly websockets .
To replace this with socket.io or any other signalling as SIP / XHR / AJAX etc , you need to replace server.js with new socket.io based code for request and response .
Follow these steps :
create a https server ( since webrtc pages capture web cam input only from secure origins) for socket.io. Assign server to an variable say app.
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync('ssl_certs/server.key'),
cert: fs.readFileSync('ssl_certs/server.crt'),
ca: fs.readFileSync('ssl_certs/ca.crt'),
requestCert: true,
rejectUnauthorized: false
};
var app = https.createServer(options, function(request, response){
request.addListener('end', function () {
file.serve(request, response);
}).resume();
});
app.listen(8081);
here server.key , server.crt and ca.crt are fake ssl certs and 8081 is the https port I have selected .
you can reuse the same https server for hosting the webpages also.
listen on this same port for socket.io using app defined earlier
var io = require('socket.io').listen(app, {
log: false,
origins: '*:*'
});
io.set('transports', [
'websocket'
]);
I choose only websocket but you can set other types of transport too such as
socket.set('transports', [
'websocket'
, 'flashsocket'
, 'htmlfile'
, 'xhr-polling'
, 'jsonp-polling'
]);
Now implement signalling specific functions and calls such as ,
io.sockets.on('connection', function (socket) {
...
socket.on('webrtc-joinchannel',function(data){
var resp=joinChannel(data);
socket.emit('resp-webrtc-joinchannel', resp);
});
...
});
Note : I am using socket.io v0.9 .
If yo want a example implementation you can view any sample projects such as here