So I moved app.listen to the top, but now it gives me an error that port is in use. I believe this is because I set up my websocket on this port, but how do I do it then?
var server = require('websocket').server, http = require('http');
var express = require('express');
var app = express();
app.listen(8080);
var socket = new server({
httpServer: http.createServer().listen(8080)
});
socket.on('request', function(request) {
var connection = request.accept(null, request.origin);
app.get('/', function(request, response) {
var id = request.query.steamid;
console.log("STEAMID:",id);
response.send("I have received the ID: " + id);
});
connection.on('message', function(message) {
connection.sendUTF(message);
});
connection.on('close', function(connection) {
console.log('connection closed');
});
});
I believe you need to listen on connection and not on request
socket.on('connection', function(sock) {
sock.on('message', function(message) {
sock.send(message);
});
sock.on('close', function() {
console.log('connection closed');
});
});
put your app.listen(3000); outside of request event.
so,your express server get chance to initialize port to listen.
Currently it is in callback of request event and it will get called once client-server connection of web-socket is established.
As far as URL concern
ws://localhost:8080/?steamid=123456789
you have configured websocket to listen on port 8080.But your express is configured to listen port 3000.So it is not possible to catch request on express Server configured on different port which is requested through web-socket configured on another different port.
url should be like this.
http://localhost:3000/?steamid=123456789
because your express server using http protocol and not websocket
Related
So, I have this app called server and the other one called client, server providers all the data for the client to consume. The thing is, when i try to emit from server (port 8080) and receive to client (port 80) nothing happens
server: app.js
var app = require ("./config/server.js");
var http = require('http').createServer(app);
var io = require("socket.io")(http);
http.listen(8080, function(){
console.log('Server side instagram_clone_v01 online');
});
io.sockets.on('connect', function (socket) {
console.log("conectou socket.id="+socket.id);
});
When the server database insert new photo, this is called:
io.emit("newPhoto");
client: app.js
var app = require('./config/server');
app.listen(80, function(){
console.log('Server client instagram_clone_v01 online');
});
var io = require('socket.io');
This is called inside a ejs code:
const socket = io.connect('http://localhost:8080', {transports: ['websocket', 'polling', 'flashsocket']});
socket.on('newPhoto',function(){
load_posts();
});
Edited with the Answer of Federico
I added io.origins('*:*'); to server, but emit isn't emitting
I don't know why you are using io.sockets.on, I couldn't find it in the documentation. I've tried to clean the code, give it a try.
server.js
var app = require ("./config/server.js");
var http = require('http').Server(app);
var io = require("socket.io")(http);
http.listen(8080, function(){
console.log('Server side instagram_clone_v01 online');
});
io.on('connect', socket => {
console.log("user" + socket.request.user.id + "connected");
socket.on('disconnect', function() {
console.log('A user has disconnected');
}
io.emit("newPhoto");
});
client.js
//io() works only when connecting to a socket hosted on the same url/server
// For connecting to an external socket hosted elsewhere, you would use io.connect('URL');
var socket = io();
socket.on('newPhoto',function(){
load_posts();
});
In the page where your user being redirected after login, you should include these scripts:
<script src="/socket.io/socket.io.js"></script>
<script src="/client.js"></script>
I am trying to build a small websocket application. I am trying to implement it on a website that already runs on a secure HTTPS protocol thus the websocket has to be on wss to work.
I build the server using the following code:
var express = require('express');
var app = express();
var fs = require('fs');
var key = fs.readFileSync('/etc/apache2/ssl/www.bigriss.com_private_key.key');
var cert = fs.readFileSync( '/etc/apache2/ssl/www.bigriss.com_ssl_certificate.crt' );
var ca = fs.readFileSync( '/etc/apache2/ssl/bigriss.com_ssl_certificate_INTERMEDIATE.crt' );
var options = {
key: key,
cert: cert,
ca: ca
};
var https = require('https').createServer(options, app);
var io = require('socket.io')(https);
var port = process.env.PORT || 8080;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
var token = socket.handshake.query.token;
io.emit('chat message', msg + token);
});
});
https.listen(port, function () {
console.log('listening on *:' + port);
});
Which would seem to me to be a quite simple and standard implementation. I can access the url https://example.com:8080 properly and it is giving the contents that are read at index.html. On this html file is where I try to establish a connection using:
var socket = io.connect('https://bigriss.com:8080/?token=abc', {
transports: ['websocket'],
upgrade: false,
secure: true,
reconnect: true,
rejectUnauthorized : false
});
Having played several times with the options. Regardless, I get an error in the Chrome Console as being:
failed: Connection closed before receiving a handshake response
failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
In the terminal I get the following node error:
nodejs: ../src/util-inl.h:196: TypeName* node::Unwrap(v8::Local<v8::Object>) [with TypeName = node::TLSWrap]: Assertion `(object->InternalFieldCount()) > (0)' failed.
Aborted
I have testing this same setup with HTTP and it works correctly. Is there anything in particular that I am missing with HTTPS?
I'm trying to implementing cluster on nodejs and using Socket.io in my application, after some search and introduced about that and finding sticky-socket-cluster i try to use that, here is sample code which i use the documentetion of library, but login socket not working and dont print log
require('sticky-socket-cluster/replace-console')();
var options = {
workers : require('os').cpus().length, // total workers (default: cpu cores count).
first_port : 8000, // 8000, 8001 are worker's ports (default: 8000).
proxy_port : 3000, // default (5000).
session_hash: function (req, res) {
return req.connection.remoteAddress;
},
no_sockets: false // allow socket.io proxy (default: false).
};
require('sticky-socket-cluster')(options, start);
function start(port) {
var express = require('express');
var http = require('http');
var app = express();
var server = http.Server(app);
var socket = require('socket.io')(server);
socket.on('connection', function (socket) {
console.log("socket.io connection handler...");
});
socket.on('login', function (data) {
console.log(data.username);
});
server.listen(port, function () {
console.log('Express and socket.io listening on port ' + port);
});
}
On client side, I have this code:
var serverAddress = "http://localhost:8081";
var socket = io(serverAddress);
socket.on('connect', function(){
console.log("Connected to server on %s", serverAddress);
});
socket.emit("xxx", {text : "attack"});
And on server, I have this one:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var socket = require('socket.io').listen(server);
socket.on('connect', function() {
console.log('A user is connected to server');
});
socket.on('xxx', function(data) {
console.log(data);
});
connect event is fired and caught on server, but xxx event isn't even fired nor caught. What's wrong? Console.log didn't report any error.
You're confusing the socket.io server with a socket.io connection.
The server receives a connection event when a new client connection is made. The argument for that event (usually called socket) represents that connection. This is the object that you need to use to listen to messages:
// server
...
var io = require('socket.io').listen(server);
...
io.on('connection', function(socket) {
console.log('A user is connected to server');
socket.on('xxx', function(data) {
console.log(data);
});
});
I have built a private chat system using Node.js and Socket.io on my local development server, and it is working fine, sends messages, updates the database whenever the client accepts the message event. However, the past two days I have been trying to push this to my live Rackspace server. I have been chatting with Rackspace and they have spun up my node server, I have a console.log that prints "Server listening on port: xxxx". I will post my node.js server code as well as some of my client code. I am just not sure what is going wrong as it worked fine on my local development. Chrome console is giving me a error of 'io is not defined' which it is, which is making me think that it is not loading the socket.io/socket.io.js from the node server. However, I thought that it would give me an error on the GET request.
I am new to Node.js and Socket.io and do not understand everything about it. I am trying to use this on vhost host, could this cause a problem?
var express = require('express');
app = require('http').createServer(handler),
//server = require('http').createServer(app),
io = require('socket.io')(app);
fs = require('fs');
app.listen(3000, function() {
console.log("Server listening on: 3000");
});
var clients = {};
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
//app.get('/', function(req, res){
// res.sendFile(__dirname + '/index.html');
//});
io.sockets.on('connection', function(socket){
console.log("Connected!");
socket.emit('news', { hello: 'world' });
socket.on('add-user', function(data){
clients[data.username] = {"socket" : socket.id};
console.log(data.username+' / '+clients[data.username].socket);
});
socket.on('private-message', function(data){
console.log("Sending: " + data.content + " to " + data.username);
if (clients[data.username]){
io.sockets.connected[clients[data.username].socket].emit("add- message", data);
} else {
console.log("User does not exist: " + data.username);
}
});
//Removing the socket on disconnect
socket.on('disconnect', function() {
for(var name in clients) {
if(clients[name].socket === socket.id) {
delete clients[name];
break;
}
}
});
});
Client Code:
var socket = io;
socket.connect('x.x.x.x:3000');
var viewingUser = $('#viewingUserID').val();
socket.on("news", function (data) {
console.log(data);
});
socket.emit("add-user", {"username" : viewingUser });
So I replaced "<script type="text/javascript" src="xx.xxx.xxx.xxx:3000/socket.io/socket.io.js">" with "<script type="text/javascript" src="https://cdn.socket.io/socket.io-1.3.5.js"></script>"
This is the error:
GET http://23.253.247.166:3000/socket.io/?EIO=3&transport=polling&t=1439565622045-29 net::ERR_CONNECTION_REFUSED
Your server does not have a request handler for the socket.io javascript file.
You browse to your website and your server gets a request, you handle it by sending the index.html file.
When the index.html file is being processed by the browser, it will find the socket.io script tag and make a request to the server for it, but you only respond to requests by sending the index.html file.
Either:
Try replacing the script tag src with a CDN version of socket.io (client version).
or
Add a request handler to send the javascript file when requested
If you have to serve static content (like webpages / javascript / css / images / ...) express makes it very easy:
app.use(express.static('public')); Where public would be the folder of your static assets.
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('index.html');
});
// Socket stuff goes here. but try this for a start
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('Server listening on:3000');
});