How to run websocket and client on different ports - node.js

I have the following client ( serves the chat interface ) and a websocket, which are connected by the http. Http at the moment runs on the port 8080. So I would like to run the client on one port and the websocket on another, but if I disconnect them by http and of course the websocket doesn´t work on the client.
So is there a way to run them on different ports but still have them connected by the http ?
server:
var express = require('express');
var app = express()
app.use(express.static(__dirname + '/public'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs')
var port = 8080;
/************************************************ */
if (process.argv.indexOf('--port') >= 0) {
port = process.argv[process.argv.indexOf('--port') + 1]
}
/************************************************ **/
var sIndexHtmlTemplate = fs.readFileSync(__dirname + '/index1.html', 'utf8');
/************************************************ ***/
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
});
io.on('connection', function (socket) {
socket.on('chat message', function (msg) {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
});
/************************************************ ***/
http.listen(port, function () {
console.log('listening on *' + port);
});

Related

WebSocket connection to 'ws://X.XXX.XXX.XXX:5858/socket.io/?EIO=3&transport=websocket' failed:

I am trying to solve this issue since a long but not getting an accurate answer on the stackoverflow.
We are checking on this URL.
http://amritb.github.io/socketio-client-tool/v1/
and getting the following error.
Connecting to: http://x.xxx.xxxx.xxx:5858/ with options: {"path":"","transports":["websocket"]}
Here is the code snippet.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const port = process.env.PORT || 5858;
var compression = require('compression');
app.use(compression());
io.on('connection', function (socket) {
// Socket connection for Drivers
socket.on('join', function (data) {
socket.join(data.room); // join room
console.log('New user joined on room:' + data.room);
console.log(data);
});
socket.on('disconnect', function () {
socket.leave(socket.room);
});
});
http.listen(port, function () {
console.log('Socket Listening on Port: ' + port);
});

connecting refused for web socket socket.io

I am loading my scripts using
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="/js/chat.js"></script>
My chat.js script is :
var socket = io();
socket.on('connect', function(){
var chatForm = document.forms.chatForm;
if (chatForm) {
var chatUsername = document.querySelector('#chat-username');
var chatMessage = document.querySelector('#chat-message');
chatForm.addEventListener("submit", function(e){
console.log("working")
//prevents page from reloading
e.preventDefault();
//emit the message with the socket
socket.emit('postMessage',{
username: chatUsername.value,
message: chatMessage.value,
});
chatMessage.value='';
chatMessage.focus();
});//chatform event
socket.on('updateMessages', function(data) {
showMessage(data);
});//update messages
}//chatForm
})
function showMessage(data) {
var chatDisplay = document.querySelector('.chat-display')
var newMessage = document.createElement('p');
newMessage.className = 'bg-success chat-text';
newMessage.innerHTML = '<strong>' + data.username + '<strong>:</strong>' +
data.message
chatDisplay.insertBefore(newMessage, chatDisplay.firstChild);
}
My app.js file uses:
app.set('port', process.env.PORT || 3000 );
var server = app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
io.attach(server);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
I am getting the following errors in my console and have no idea how to fix them. Somebody please help!
The server is listening on port 3000. My console is saying that there is an unhandled 'error' event
In your app.js file, you should connect socketIO before listening:
const socketIO = require('socket-io');
const io = socketIO(app);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
app.set('port', process.env.PORT || 3000 );
app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
Let try it, because I think after listening, everything won't work. We should connect socketIO before listening.

In openshift Nodejs Socket.io responce 200 Ok, But console.log value not visible. my socket is working?

created index.js (server)
var express = require('express');
var app = express();
///creating server
var server = require('http').createServer(app);
var io = require('socket.io').listen(server, { origins:'http://nodejs-atnodejs.rhcloud.com:8000' });
below is remaining code
Routing to index.html page
app.get('/', function (req, res) {
console.log('in socket---' + res);
res.sendfile('index.html');
});
///socket connection
io.sockets.on('connection', function (socket) {
socket.on('chatmessage', function (msg) {
io.emit('chatmessage', msg);
console.log('in socket---' + data);
});
});
/// Listen to Openshift port
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);
created index.html(client)
src="http://nodejs-atnodejs.rhcloud.com:8000/socket.io/socket.io.js
var socket = io.connect('http://nodejs-atnodejs.rhcloud.com:8000');
console.log('this is index page');
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
socket.emit('chatmessage', { my: 'data' });
});
When accessed from browser:
Problem is not getting "console.log('chatmessage---' + data);" which is inside the socket..
and keep on getting xhr-polling../t=xxxxx responses..
is my socket working properly?
Both your browser and server code is listening for an event of 'chatmessage' after connection either your browser or server should be emitting the event first and than the other should be listening such as...
// server
io.sockets.on('connection', function (socket) {
socket.emit('chatmessage', /*some data*/);
});
//client
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
});

I'm unable to connect to socket

I'm trying to connect to a socket.But I did not get the socketid on the console.Is it the right way of connecting to a socket ?Can anyone please suggest me ...
My code :
var app = express();
var dir = process.cwd();
app.use(express.static(dir)); //app public directory
app.use(express.static(__dirname)); //module directory
var server =require('http').createServer(app);
var io = require('socket.io')(server);
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
client code :
var socket = io('http://localhost:8085/socket_issue');
socket.on('connect', function(){ console.log('connected to socket'); });
socket.on('error', function(e){ console.log('error' + e); });
socket.on( 'news', function( data ){
console.log(data);
});
socket.on('disconnect', function(){});
You seem to not have a server.listen() in your backend code.
I've edited the server code and it functions correctly:
var app = require('express')();
var dir = process.cwd();
var server =require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
Don't forget to change the port on the front-end and it'll work as expected:
Socket connected :Y7zi7dLRxqBA5nakAAAA

Can't seem to get socket io to display any emits

I've been trying to figure out why I can't get any emits to show up in my terminal and it seems that everything is running fine.... except for seeing the emits. Here is my code
var express = require('express');
var path = require('path');
// Create a new Express application
var app = express();
var views = path.join(process.cwd(), 'views');
app.use("/static", express.static("public"));
// Create an http server with Node's HTTP module.
// Pass it the Express application, and listen on port 3000.
var server = require('http').createServer(app).listen(3000, function() {
console.log('listening on port ' + 3000)
});
// Instantiate Socket.IO hand have it listen on the Express/HTTP server
var io = require('socket.io')(server);
var game = require('./game');
app.get('/', function(req,res) {
res.sendFile(path.join(views, 'index.html'));
});
io.on('connect', function(socket) {
io.emit('connection', { message: "You are connected!" });
game.initGame(io, socket);
socket.emit('connected', { message: "You are connected!" });
io.sockets.emit('test', 'test')
});
Any help would be great!
Emits are not automatically printed. socket.emit will send a message back to the client, not to the terminal. Use console.log("whatever") to print to the terminal:
io.on('connect', function(socket) {
console.log('Client connected');
socket.on('test', function(data) {
console.log("Got message of type 'test'containing data:", data);
});
});

Resources