connecting refused for web socket socket.io - node.js

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.

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);
});

How to run websocket and client on different ports

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);
});

socket.io client not receiving message

When no room is specified client receive the message but when specify a room I am unable to receive message on client.
server.js
var socket = require('socket.io');
var mysql = require('mysql');
const path = require('path');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = PORT;
io.on('connection', (socket) => {
console.log('new connection made');
socket.on('subscribe', function (room) {
socket.room = room;
socket.join(socket.room, function () {
console.log('joined:' + room); // outputs joined: 1
socket.on('send-message', (data) => {
io.to(data.room).emit('message-received', data.message);
console.log("sent to room:" + data.room); // outputs sent to room: 1
});
});
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
client.js
this.socket = io.connect('ws://IP:PORT');
this.socket.on('connect', () => {
console.log("connection made"); // it output connection made in console
this.socket.emit('subscribe', 1);
});
this.socket.on('message-received', (message: any) => {
console.log(message);
});
on server.js I have tried several options below but still unable to emit 'message-received' on client side:
// io.emit('message-received', data);
// io.to(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
// io.sockets.in(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
//io.broadcast.to(data.room).emit('message-received', data.message);
using latest socket.io library with angular 4
based on what i see on your clientside and serverSide code, I believe the problem is in the clientSide code...
On your server, inside the 'subscribe' event the server is also listening for 'send-message' event, which you're never emiting from the client side!!
Therefore, if you emit 'send-message' event with data(this should include message) as parameter, only then the server would emit 'message-received' event to the client..
HOPE THIS HELPS!

Unable to redirect to a url using http node proxy

I am deploying my node.js chat server on the server.Now on server the Https is enabled on port 8443 and my server runs on port 3000.Now whenever i deploy my node.js express server on the server it starts listening but whenever i try to open the page in my browser "Segmentation Fault" is written on my dedicated Server console.I have double checked my certificates they are fine Can anyone guide me here that what would be the thing causing the issue? is that a port related issue or its a code related issue?
// Setup basic express server
var express = require('express');
var app = express();
var fs = require('fs');
var httpProxy=require('http-proxy');
var proxy = httpProxy.createProxyServer({});
var options = {
key: fs.readFileSync('/etc/pki/tls/private/demo.iproctoring.com.key'),
cert: fs.readFileSync('/etc/pki/tls/certs/demo.iproctoring.com.cer')
};
var server = require('https').createServer(options,app,function(req,res)
{
proxy.web(req, res, { target: 'https://demo.iproctoring.com:8443' });
});
var io = require('../..')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
app.use(express.static(__dirname + '/public'));
var numUsers = 0;
io.on('connection', function (socket) {
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
if (addedUser) {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});

Node.js socket.io server callback not working

I'm working on a simple Node.js bi-directional client\server communication channel and I'm attempting to use socket.io on the server and socket.io-client on the client.
I've inserted the code below, as you'll see it's pretty basic stuff, and I'm running both on my local machine - to minimise complexity.
The behaviour I'm seeing is:
I start the server.
The server logs 'Server started' to the console.
I start the client.
The client logs 'Server is ready!'
Nothing else happens...
What I'd expect is the server to log a 'Client is ready!' message and then the content ('Ready received').
I've even used WireShark to sniff the line and it does appear that the client is emitting the message, as designed - but the callback on the server isn't firing.
I'm running node v0.8.4 with express v3.1.0, socket.io v0.9.13 and socket.io-client v0.9.11 (all installed via npm).
Here's the server code...
var http = require('http'),
express = require('express'),
app = express(),
server = http.createServer(app);
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
server.listen(8080);
console.log("Server started");
var io = require('socket.io').listen(server);
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
And here's the client code...
var clientio = require('socket.io-client');
var socket = new clientio.connect('http://localhost', { port: 8080 });
socket
.on('server ready', function(data){
console.log('Server is ready!');
socket.emit('comms', 'Ready received');
})
.on('connect-error', function(error) {
console.log('Connection Error\n' + error);
})
.on('error', function(error) {
console.log('Socket Error\n' + error);
})
The documentation and examples for both socket.io and socket.io-client are somewhat confused (to be charitable) and they appear to be a bit of a moving target... but from what I can tell, I think this should work.
I'm hoping someone can give me advice as to where I'm going wrong?
In your server you have this code:
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
What you should do is something like this:
io.sockets.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' });
socket.on('comm', function(content){
console.log('Client is ready!');
console.log(content);
});
});
hopefully this is doing more or less what you need it to do. Just a couple of minor changes.
app.js
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
// using 'connect' to handle static pages
app.use(require('connect').static(__dirname + '/public'))
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('server ready', { msg: 'ready' });
socket.on('comms', function(content) {
console.log(('Client is ready\n'));
console.log(content);
});
});
index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
window.jQuery || document.write('<script src="js/jquery-1.8.3.min.js"><\/script>')
</script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
(function (d, b) {
function bindEvents() {
function doSomething(msg) {
$.each(msg, function (key, value) {
console.log('doSomething...');
$("body").append("<p>" + value + "</p>")
});
};
// var socket = io.connect();
var socket = io.connect('http://localhost');
socket.on('server ready', function (msg) {
console.log('Server is ready!\n', msg);
doSomething(msg);
socket.emit('comms', {
msg: 'Client is Ready'
});
});
socket.on('connect-error', function (err) {
console.log('Connection Error\n', err);
});
socket.on('error', function (err) {
console.log('Connection Error\n', err);
});
};
$(document).ready(function () {
bindEvents()
});
})(jQuery, this)
</script>

Resources