socket.io send message twice - javascript

I am trying to create realtime chat in my SPA app. I got the chat working , but when I move to another page and head back to the chat page , it starts loading messages twice. Here is my server side for socket.io:
var io = require('socket.io').listen(app.listen(config.port));
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'You are chatting now !' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
I tried using io.sockets.once instead of io.sockets.on but it doesn't show chat 2nd time ..
And here is my client side together with html (jade template engine):
#content(style='width: 500px; height: 300px; margin: 0 0 20px 0; border: solid 1px #999; overflow-y: scroll;')
input#field(style='width:350px;')
input#send(type='button', value='send')
script(src='/socket.io/socket.io.js')
script.
$("#field").keyup(function(e) {
if(e.keyCode == 13) {
sendMessage();
}
});
var messages = [];
var socket = io.connect('localhost:3030/#/chat');
var field = document.getElementById("field");
var sendButton = document.getElementById("send");
var content = document.getElementById("content");
socket.on('message', function (data) {
if(data.message) {
messages.push(data.message);
var html = '';
for(var i=0; i<messages.length; i++) {
html += messages[i] + '<br />';
}
content.innerHTML = html;
content.scrollTop = content.scrollHeight;
} else {
console.log("There is a problem:", data);
}
});
sendButton.onclick = sendMessage = function() {
var text = field.value;
socket.emit('send', { message: text });
field.value = '';
};
I want to fix this , so when I go back 2nd time it doesnt show 2 times , or for 3rd time to show it 3 times and so on ... Help is greatly appreciated :)

If I understand correctly, you want correct persistence between page refreshes, just add an array on the server to collect the messages and tell new connections all about them.
I really just use the docs to accomplish my goals (link for reference http://socket.io/docs/server-api/)
for the code below to run, it is necessary to do these commands in the working directory
npm install express
npm install socket.io
(server code)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
//serve up the file, the code for this is below, I translated your jade to html
app.get('/', function(req, res){
res.sendfile('index.html');
});
//note this will get big eventually with lots of users
var message_past = [];
io.on('connection', function(socket){
socket.emit('server-message', { message: 'Welcome !' });
// tell user recent posts
for (var i = 0; i < 20 && !!message_past[i] ; i ++) socket.emit('user-message',message_past[i]);
// save the message and update everyone with it
socket.on('user-message', function (data) {
message_past.push(data);
// io.emit will tell everyone <-- I think what you want
// socket.broadcast.emit will tell everyone but this socket
// socket.emit will tell just this socket
io.emit('user-message', data);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and the client code
<input id='field' type="text" style='width:350px;'/>
<input id='send' type='button' value='send'/>
<div id='content' style='width: 500px; height: 300px; margin: 0 0 20px 0; border: solid 1px #999; overflow-y: scroll;'>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src='/socket.io/socket.io.js' ></script>
<script type="text/javascript">
$("#field").keyup(function(e) {
if(e.keyCode == 13) {
sendMessage();
}
});
var socket = io.connect('localhost:3000/#/chat');
console.log(socket)
var field = document.getElementById("field");
var sendButton = document.getElementById("send");
var content = document.getElementById("content");
var display_message = function( data ) {
if(data.message) {
$(content).append(data.message+'<br/>');
content.scrollTop = content.scrollHeight;
} else {
console.log("There is a problem:", data);
}
};
socket.on('server-message', display_message);
socket.on('user-message', display_message);
sendButton.onclick = sendMessage = function() {
var text = field.value;
socket.emit('user-message', { message: text });
field.value = '';
};
</script>

Related

Can't get socket.io event from server

I'm making a Socket.IO app, and trying to add a client-side listener for an event, in addition to a listener I already have. The problem is that the existing code is quite hard for me to make sense of, as I didn't write sections of it and am new to Socket.IO, so I don't know where to put my second event listener.
I've tried adding it in right before and after my first event listener, with no success.
The existing code, with one socket.on listener, besides 'connect':
$(function () {
var socket = io();
socket.on('connect', function(){
var id = socket.io.engine.id;
document.getElementById("os").innerHTML = id
});
$('form').submit(function(){
socket.emit('chat message', $('#m').val())
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
var form = $('#m').val();
//logic for commands
var help = /#help/;
var kill = /#kill/;
var admin = /SUDO/;
var private = /#to/;
var one = help.test(msg);
var two = kill.test(msg);
var three = admin.test(msg);
var four = private.test(msg);
if (one == true) {
$('#messages').append($('<li>').text('[SYSTEM]: The "#help" command has been activated. The following is an automated response and the user message which activated #help will appear below it in the chat stream. '));
$('#messages').append($('<li>').text("[#HELP]: This message is a brief overview of how to use Megaphone: type a message into the bar above, and hit enter to send it. Refresh the window to clear messages, and to leave, simply close the tab."));
function delay(ms, cb) { setTimeout(cb, ms) }
document.title = "New Message!";
audio.play();
delay(5000, function() {
document.title = "Megaphone";
})
} if (two == true && three == true) {
location = "https://google.com"
} if (two == true && three == false) {
$('#messages').append($('<li>').text(' [SYSTEM]: ATTEMPTED ACCESS TO AN ADMIN COMMAND DETECTED. THE COMMAND CANNOT BE USED WITHOUT AN ADMIN PASSPHRASE.'));
function delay(ms, cb) { setTimeout(cb, ms) }
document.title = "New Message!";
audio.play();
delay(5000, function() {
document.title = "Megaphone";
})
} if (three == true) {
var adminmsg = msg.split('SUDO')[1]
$('#messages').append($('<li>').text(' [ADMIN]: ' + adminmsg));
function delay(ms, cb) { setTimeout(cb, ms) }
document.title = "New Message!";
audio.play();
delay(3000, function() {
document.title = "Megaphone";
})
} if (four == true) {
var privatemessage = msg.split('#to')[0];
var recipientid = msg.split('#to')[1];
socket.emit('private message', { recipient: recipientid, message: privatemessage });
} else {
$('#messages').append($('<li>').text(' [USER]: ' + msg));
function delay(ms, cb) { setTimeout(cb, ms) }
document.title = "New Message!";
audio.play();
delay(5000, function() {
document.title = "Megaphone";
})
};
});
});
The event listener I'd like to add:
socket.on("dm", function(data) {
alert(data.description);
}
Server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.get('/about', function(req, res){
res.sendFile(__dirname + '/about.html');
});
http.listen(3000, function(){
console.log('listening on *:3000. Megaphone is functional.');
});
io.on('connection', function(socket) {
console.info(`Client connected [id=${socket.id}]`);
socket.on('disconnect', function(){
console.info(`Client gone [id=${socket.id}]`);
});
});
io.on('connection', function(socket){
socket.on('private message', ({ recipient, message }) => {
io.to(recipient).emit("dm", {description: message});
console.info(message + ' ' + recipient)
})
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
When I insert the second event listener right before or after the first, it doesn't seem to work as there's no alert.

Response.write() or .toString() (bug?) on NodeJS server

I am a trying to make a small web server for testing. I made it with NodeJS. But something unexpected happened. The webpage passed by the NodeJS server couldn't be displayed properly. But the webpage worked perfectly when I used php+Apache. When I opened the source code received at my client side, there are no observable difference. Here is my code:
Server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var Max = 30;
var port = process.argv[2];
var server = http.createServer( function (request, response) {
var pathname = url.parse(request.url).pathname; if (pathname == "") pathname = "index.html";
console.log("Request for " + pathname + " received.");
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
} else {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(port);
console.log('Server running at http://127.0.0.1:8081/');
var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {
var socketId = nextSocketId++;
sockets[socketId] = socket;
console.log('socket', socketId, 'opened');
socket.on('close', function () {
console.log('socket', socketId, 'closed');
delete sockets[socketId];
});
socket.setTimeout(4000);
});
function anyOpen(array) {
for (var ele in array) {
if (ele) return true;
}
return false;
}
(function countDown (counter) {
console.log(counter);
if (anyOpen(sockets)) {
return setTimeout(countDown, 1000, Max);
} else if (counter > 0 ) {
return setTimeout(countDown, 1000, counter - 1);
};
server.close(function () { console.log('Server closed!'); });
for (var socketId in sockets) {
console.log('socket', socketId, 'destroyed');
sockets[socketId].destroy();
}
})(Max);
Chatroom2-0.php
<!DOCTYPE html>
<html>
<head>
<style>
textarea {
width:95%;
rows:50;
height:80%;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script type="text/javascript">
var str = "";
function enter(e){
if (e.keyCode == 13 && document.getElementById("Input").value) {
//alert("Enter!!!!");
sendInput();
document.getElementById("Input").value = "";
}
};
function updateBoard() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("MsgBoard").innerHTML = xmlhttp.responseText;
}
var textarea = document.getElementById('Output');
textarea.scrollTop = textarea.scrollHeight;
};
xmlhttp.open("POST","Server.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Username&Content="+document.getElementById("Username").value);
};
function sendInput() {
username = document.getElementById("Username").value; if (!username) username = "Gotemptyname";
msg = document.getElementById("Input").value; if (!msg) msg = "GotNothing";
if (msg) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","Server.php",true);
//xmlhttp.open("POST","test.txt",true);
//xmlhttp.send();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Message&Username="+username+"&Content="+msg);
//alert(xmlhttp.responseText);
}
};
</script>
</head>
<body onload="setInterval('updateBoard()',1000)">
<div id="MsgBoard"></div>
<form name="UsrInput">
<?php
if (isset($_POST["Username"]))
echo '<input type="text" id ="Username" value="'.$_POST["Username"].'" disable>';
else {
header("Location: /login/index.html");
die();
}
?>
<input type="text" id="Input" onkeypress="enter(event)" value="" >
</form>
</body>
</html>
Users should be able to access the Chatroom2-0.php after login. The login functionality is also ok. But when I entered the Chatroom2-0.php, I got a String, next to my textbox.
'; else { header("Location: /login/index.html"); die(); } ?>
I noticed that the string is part of my php code in the file. I don't know what's happening. I think this might have something to do with the response.write() or the data.toString() function. Maybe the function changed something in my coding? How could I solve this problem.
Anyway, I appreciate for any help given.
The problem is that you are trying to run php code on a nodejs server. There is no solution to this, as node is not a php interpreter, so it sees everything as html text; thus your php code appearing on the page. You need to create an entirely different html for the node project.

How can I make my server accessible for everyone?

I created (I copied) a chat server using Node.JS and the server is on my LocalHost: 127.0.0.1, only I can use the chat, but I want that anyone can use the server too, so I want to know how to put this Chat server in my real server:
http://sistema.agrosys.com.br/sistema/padrao/HTML5/WebSocket/
And : http://calnetaskmanager.herokuapp.com/
But I don't now how to put my chat-server.js into my Heroku Server.
What should I do to make it possible.
Thanks in advance
If you want to see what happens: client side on my server
Client Side:
$(function() {
"use strict";
// for better performance - to avoid searching in DOM
var content = $('#content');
var input = $('#input');
var status = $('#status');
// my color assigned by the server
var myColor = false;
// my name sent to the server
var myName = false;
// if user is running mozilla then use it's built-in WebSocket
window.WebSocket = window.WebSocket || window.MozWebSocket;
// if browser doesn't support WebSocket, just show some notification and exit
if (!window.WebSocket) {
content.html($('<p>', {
text: 'Sorry, but your browser doesn\'t ' + 'support WebSockets.'
}));
input.hide();
$('span').hide();
return;
}
// open connection
var connection = new WebSocket('ws://127.0.0.1:1337');
connection.onopen = function() {
// first we want users to enter their names
input.removeAttr('disabled');
status.text('Choose name:');
};
connection.onerror = function(error) {
// just in there were some problems with conenction...
content.html($('<p>', {
text: 'Sorry, but there\'s some problem with your ' + 'connection or the server is down.'
}));
};
// most important part - incoming messages
connection.onmessage = function(message) {
// try to parse JSON message. Because we know that the server always returns
// JSON this should work without any problem but we should make sure that
// the massage is not chunked or otherwise damaged.
try {
var json = JSON.parse(message.data);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ', message.data);
return;
}
// NOTE: if you're not sure about the JSON structure
// check the server source code above
if (json.type === 'color') { // first response from the server with user's color
myColor = json.data;
status.text(myName + ': ').css('color', myColor);
input.removeAttr('disabled').focus();
// from now user can start sending messages
} else if (json.type === 'history') { // entire message history
// insert every single message to the chat window
for (var i = 0; i < json.data.length; i++) {
addMessage(json.data[i].author, json.data[i].text,
json.data[i].color, new Date(json.data[i].time));
}
} else if (json.type === 'message') { // it's a single message
input.removeAttr('disabled'); // let the user write another message
addMessage(json.data.author, json.data.text,
json.data.color, new Date(json.data.time));
} else {
console.log('Hmm..., I\'ve never seen JSON like this: ', json);
}
};
/**
* Send mesage when user presses Enter key
*/
input.keydown(function(e) {
if (e.keyCode === 13) {
var msg = $(this).val();
if (!msg) {
return;
}
// send the message as an ordinary text
connection.send(msg);
$(this).val('');
// disable the input field to make the user wait until server
// sends back response
input.attr('disabled', 'disabled');
// we know that the first message sent from a user their name
if (myName === false) {
myName = msg;
}
}
});
/**
* This method is optional. If the server wasn't able to respond to the
* in 3 seconds then show some error message to notify the user that
* something is wrong.
*/
setInterval(function() {
if (connection.readyState !== 1) {
status.text('Error');
input.attr('disabled', 'disabled').val('Unable to comminucate ' + 'with the WebSocket server.');
}
}, 3000);
/**
* Add message to the chat window
*/
function addMessage(author, message, color, dt) {
content.prepend('<p><span style="color:' + color + '">' + author + '</span> # ' +
+(dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':' + (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) + ': ' + message + '</p>');
}
});
* {
font-family: tahoma;
font-size: 12px;
padding: 0px;
margin: 0px;
}
p {
line-height: 18px;
}
div {
width: 500px;
margin-left: auto;
margin-right: auto;
}
#content {
padding: 5px;
background: #ddd;
border-radius: 5px;
overflow-y: scroll;
border: 1px solid #CCC;
margin-top: 10px;
height: 160px;
}
#input {
border-radius: 2px;
border: 1px solid #ccc;
margin-top: 10px;
padding: 5px;
width: 400px;
}
#status {
width: 88px;
display: block;
float: left;
margin-top: 15px;
}
<!DOCTYPE html>
<html>
<head>
<style type="text/css"></style>
<meta charset="utf-8">
<title>WebSockets - Simple chat</title>
</head>
<body>
<div id="content"></div>
<div>
<span id="status">Choose name:</span>
<input type="text" id="input">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="./frontend.js"></script>
</body>
Server Side
// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
"use strict";
// Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'node-chat';
// Port where we'll run the websocket server
var webSocketsServerPort = 1337;
// websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');
/**
* Global variables
*/
// latest 100 messages
var history = [];
// list of currently connected clients (users)
var clients = [];
/**
* Helper function for escaping input strings
*/
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<')
.replace(/>/g, '>').replace(/"/g, '"');
}
// Array with some colors
var colors = ['red', 'green', 'blue', 'magenta', 'purple', 'plum', 'orange'];
// ... in random order
colors.sort(function(a, b) {
return Math.random() > 0.5;
});
/**
* HTTP server
*/
var server = http.createServer(function(request, response) {
// Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});
/**
* WebSocket server
*/
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server. WebSocket request is just
// an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
httpServer: server
});
// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
// accept connection - you should check 'request.origin' to make sure that
// client is connecting from your website
// (http://en.wikipedia.org/wiki/Same_origin_policy)
var connection = request.accept(null, request.origin);
// we need to know client index to remove them on 'close' event
var index = clients.push(connection) - 1;
var userName = false;
var userColor = false;
console.log((new Date()) + ' Connection accepted.');
// send back chat history
if (history.length > 0) {
connection.sendUTF(JSON.stringify({
type: 'history',
data: history
}));
}
// user sent some message
connection.on('message', function(message) {
if (message.type === 'utf8') { // accept only text
if (userName === false) { // first message sent by user is their name
// remember user name
userName = htmlEntities(message.utf8Data);
// get random color and send it back to the user
userColor = colors.shift();
connection.sendUTF(JSON.stringify({
type: 'color',
data: userColor
}));
console.log((new Date()) + ' User is known as: ' + userName + ' with ' + userColor + ' color.');
} else { // log and broadcast the message
console.log((new Date()) + ' Received Message from ' + userName + ': ' + message.utf8Data);
// we want to keep history of all sent messages
var obj = {
time: (new Date()).getTime(),
text: htmlEntities(message.utf8Data),
author: userName,
color: userColor
};
history.push(obj);
history = history.slice(-100);
// broadcast message to all connected clients
var json = JSON.stringify({
type: 'message',
data: obj
});
for (var i = 0; i < clients.length; i++) {
clients[i].sendUTF(json);
}
}
}
});
// user disconnected
connection.on('close', function(connection) {
if (userName !== false && userColor !== false) {
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
// remove user from the list of connected clients
clients.splice(index, 1);
// push back user's color to be reused by another user
colors.push(userColor);
}
});
});
you need to host your Node.js code somewhere, for example on Heroku, they have free plans for Node.js, you will then be given a public url, which you can distribute to others
Make it available to everyone... This is easy.
Deploy your code to a publicly available host -- say Heroku as
mentioned by #dark_ruby in his answer.
Provide a computing device with a browser (a nexus 7 will do) to
every person in the entire world
Configure it to have your service as the default home page
Done.

Nodejs and webSockets, triggering events?

I am new to this, I built a standard web chat application and I see the power of nodejs, express, socket.io.
What I am trying to do is trigger events from a phone to a website, like a remote control. There is server javascript that listens to events from the client, and client javascript that triggers those events, this is how I understand it correct me if I am wrong.
I learned in the chat app I can send an object from anywhere, as long as they are connected to my server through a specific port http://my-server-ip:3000/. Basically all events are inside the index page, and the connection is index to server to index.
What I am trying to learn is how to trigger events from an external page, I've seen things like http://my-server-ip:3000/ws or something like that, the idea is to connect to a mobile interface that isn't the actual index or website itself, but this interface communicates with the node server using it as a dispatcher to trigger events on the main index page.
Basically what I have learned was index to server to index. I am not sure how I can go custom-page to server to index.
I see that in my app.js, my understanding is that the socket listens to sends which is on the client then it emits the message.
io.sockets.on('connection', function (socket) {
socket.on('sends', function (data) {
io.sockets.emit('message', data);
});
});
I tried creating a test.html that has a button on it, I tried listening to it, here is a screen shot.
Here is my client code
window.onload = function() {
var messages = [];
var socket = io.connect('http://my-server-ip:3000/');
var socketTwo = io.connect('http://my-server-ip:3000/test.html');
var field = document.getElementById("field");
var sendButton = document.getElementById("send");
var content = document.getElementById("content");
var name = document.getElementById("name");
var trigBtn = document.getElementById("trigger-btn");
socket.on('message', function (data) {
if(data.message) {
messages.push(data);
var html = '';
for(var i=0; i<messages.length; i++) {
html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
html += messages[i].message + '<br />';
}
content.innerHTML = html;
} else {
console.log("There is a problem:", data);
}
});
//FROM DEMO
// sendButton.onclick = sendMessage = function() {
// if(name.value == "") {
// alert("Please type your name!");
// } else {
// var text = field.value;
// socket.emit('send', { message: text, username: name.value });
// field.value = "";
// }
// };
//I include this javascript with test.html and trigger
//this button trying to emit a message to socketTwo
trigBtn.onclick = sendMessage = function() {
socketTwo.emit('send', { message: 'String test here' })
}
}
I am sure that is all wrong, but hopefully this makes sense and someone can help me trigger events from another page triggering to the index.
Here is my app.js server code
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server); // this tells socket.io to use our express server
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/test.html', function(req, res) {
res.send('Hello from route handler');
});
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
All code posted above is just testing cookie cutter code, I am learning from scratch so the above can be totally changed, it's just there as a starter point.
This is so cool I got it to work, so my logic was correct. There were just a few things I was missing. Here it is.
I am not going to post all the server side javascript code, but here is the main logic after listening to the port etc.
// Set a route and in a very dirty fashion I included a script specific
// for this route, earlier I was using one script for both route.
// I also forgot to include the socket.io hence the error in the image above.
app.get('/test', function(req, res) {
res.send('<script src="/socket.io/socket.io.js"></script><script type="text/javascript" src="javascripts/trigger.js"></script><button id="test" class="trigger-btn">Trigger</button>');
});
// This listens to `send` which is defined in the `test` route
// Upon this action the server emits the message which
// is defined inside the index main route I want stuff displayed
io.sockets.on('connection', function (socket) {
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
Here is what the index client,js script looks like
window.onload = function() {
var messages = [];
var socket = io.connect('http://my-server-ip:3000');
var content = document.getElementById("content");
socket.on('message', function (data) {
if(data.message) {
messages.push(data);
var html = '';
for(var i=0; i<messages.length; i++) {
html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
html += messages[i].message + '<br />';
}
content.innerHTML = html;
} else {
console.log("There is a problem:", data);
}
});
}

websocket server not receiving message

First I built a websocket server using node js and ws module. Then using chrome and firefox, I connect to that server and the connection is successfully established. However, the message I send from browsers does not arrive at the server. I have some code on server to console.log out if message is received. Nothing appears, however when I refresh the browser, the messages I previously sent arrive. The messages did not arrive when sent them but only once I refresh the page. I don't know why. This seems to work in from some other computers but not mine.
Here is the server code:
var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express();
app.use(express.static(__dirname + '/views'));
var rmi = require('./RMIClient.js');
console.log(rmi);
var server = http.createServer(app);
server.listen(8080);
var wss = new WebSocketServer({server: server});
// from here is the logic codes
var clients = [];
var clientId = 0;
wss.on('connection', function(ws) {
console.log("connection established for client "+ (clients.length+1));
clients.push(ws);
console.log("index is " + clients.indexOf(ws));
clientId += 1;
ws.send("Hello Client: " + clientId);
//
// ws.send("Welcome from AMTT Chatting Server");
ws.on('message',function(data){
console.log('message receieved : '+data);
for(var i = 0;i<clients.length;i++){
clients[i].send(data);
}
});
ws.on('a',function(){
console.log("a event fire from client");
});
ws.on('close', function() {
var index = clients.indexOf(ws);
console.log('stopping client interval '+index);
if (index > -1) {
clients.splice(index, 1);
}
});
});
Here is the client code:
<html>
<script>
//var ws = new WebSocket('ws://localhost:8080/');
var messagearea,inputarea,sendButton;
var connection = new WebSocket(/*'wss://echo.websocket.org');*/'ws://192.168.8.195:8080/');
// When the connection is open, send some data to the server
console.log(connection.readyState);
connection.onopen = function () {
console.log(connection.readyState);
inputarea.disabled = false;
sendButton.disabled = false;
};
// Log errors
connection.onerror = function (error) {
console.log('sorry connection fail:' + JSON.stringify(error));
};
// Log messages from the server
connection.onmessage = function (e) {
messagearea.value = messagearea.value + '\n' + e.data;
console.log('Server: ' + e.data);
};
function sendMessage(){
if(inputarea.value !='')
connection.send(inputarea.value);
inputarea.value = '';
}
</script>
<body>
<textarea rows="15" cols="100" id="messagearea" disabled>
</textarea>
<br/>
<textarea rows="2" cols="90" id="inputarea" required autofocus>
</textarea>
<input type = 'button' value = 'send' id = 'sendbutton' onclick = "sendMessage()"/>
</body>
<script>
messagearea = document.getElementById('messagearea');
messagearea.value = '';
inputarea = document.getElementById('inputarea');
inputarea.value = '';
inputarea.disabled = true;
sendButton = document.getElementById('sendbutton');
sendButton.disabled = true;
</script>
</html>
And again I found that kind of situation when I develop that code in java and deployed in wildfly server. I am lost. I think there is something concerned with my network card. Because that same code work perfectly in my friend's machine.
Does anybody experience this situation ? or any solution?
You can also try the following:
connection.addEventListener("message", function (e) {
processSocketMessage(e);
});
good luck :)

Categories

Resources