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 :)
Related
Following part of my code is used for retrieving the data from TI sensor tag. So we are using sensortag node.js module to get the data and sending it to client using socket.io. on local host the application is working fine but , when i push the code to heroku cloud web sockets part is not working.
Error : the server responded with a status of 400 (Bad Request)
https://peaceful-plateau-6281.herokuapp.com/socket.io/?EIO=3&transport=polling&t=1449192192332-3 400 (Bad Request)
Following is my code :
var express = require('express');
var port = process.env.PORT || 3000;
var app = module.exports.app = express();
var server = require('http').Server(app);
//var io = require('socket.io')(server);
var SensorTag = require('sensortag');
var path = require('path');
var io = require('socket.io').listen(server.listen(port,function(){
console.log("We have started our server on port " + server.address().port);
// SensorTag.discover(function(tag) { and close it with }); above ondiscover mthod
function onDiscover(tag){
tag.on('disconnect', function() {
console.log('disconnected!');
process.exit(0);
});
function connectAndSetUpMe() { // attempt to connect to the tag
console.log('connectAndSetUp' + tag.id);
tag.connectAndSetUp(enableDataPoints); // when you connect, call enableIrTempMe
}
function enableDataPoints(){
console.log('enabling Temp datapoint');
tag.enableIrTemperature(notifyMe);
tag.enableHumidity(notifyHumd);
tag.enableBarometricPressure(notifyPress);
tag.enableAccelerometer(notifyAccel);
}
function notifyMe(){
console.log("notifying temp datapoints");
tag.notifyIrTemperature(listenForReading);
}
function notifyHumd(){
console.log("notifying humd datapoints");
tag.notifyHumidity(listenForHumdReading);
}
function notifyPress(){
console.log("notify pressure");
tag.notifyBarometricPressure(listenForPress);
}
function notifyAccel(){
console.log("notify Accerlerometer");
tag.notifyAccelerometer(listenForAcc);
}
function listenForReading(){
tag.on('irTemperatureChange', function(objectTemp, ambientTemp) {
console.log('\tObject Temp = %d deg. C', objectTemp.toFixed(1));
function TempChange() {
io.sockets.emit('objTemp', { sensorId:tag.id, objTemp: objectTemp, ambTemp: ambientTemp});
};
TempChange();
});
}
connectAndSetUpMe();
}
SensorTag.discover(onDiscover);
})
);
io.on('connection', function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
And at the client side
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
<script>
var socket = io.connect("\/\/"+window.location.hostname+":"+location.port);
//var socket = io.connect(window.location.hostname);
console.log("window.location.hostname"+location.port);
socket.on('objTemp', function(data) {
$('#objTemp').html(parseInt(data.objTemp));
console.log("This is my places");
$('#ambTemp').html(parseInt(data.ambTemp));
</script>
</head>
<body>
<p id="objTemp"></p>
</body>
</html>
I am not getting the data at the client side through websockets.Can anybody please help me out.
Thanks®ards,
Shivadeepthi
I had the same error and just fixed.
var io = require('socket.io').listen(server);
io.set('origins', '*:*');
io.set('match origin protocol', true);
I'm trying to implement a websocket server in node.js without using any framework.
Sending messages from client to server is working fine. But now I tried to send a text file from client to server. I can see the content on the server side by using console.log in the terminal.
But:
how can i get the file information ? (name, created/edited date, etc. ?)
how can i save the file ?
Client code:
(function () {
'use strict';
var output, ws;
//Display logging information in the document
function log(s) {
var p = document.createElement("p");
p.style.wordWrap = "break-word";
p.textContent = s;
output.appendChild(p);
//Also log information on the javascript console
window.console.log(s);
}
//Send a message on the Websocket
function sendMessage(msg) {
console.log(ws.binaryType);
ws.send(msg);
console.log("Message sent");
}
//Initialize WebSocket connection and event handlers
function setup() {
output = document.getElementById("output");
ws = new window.WebSocket("ws://localhost:9999/");
//Listen for the connection open event then call the sendMessage function
ws.onopen = function () {
console.log("Connected");
document.getElementById('fl').onchange = function() {
sendMessage(document.querySelector('input[type="file"]').files[0]);
};
sendMessage("Hello Galileo!");
}
//Listen for the close connection event
ws.onclose = function (e) {
if(this.readyState == 2){
console.log('Connection is closing (Closing Handshake).')
}
else if(this.readyState == 3){
console.log('Connection closed. Has been closed or could not be opened.')
}
else{
console.log('Unhandled ReadyState: ',this.readyState);
}
console.log("Disconnected: " +
' reason:' + e.reason +
' was clean:' + e.wasClean +
' code:' + e.code);
}
//Listen for connection errors
ws.onerror = function (e) {
console.log("Error: " + e);
}
//Listen for new messages arriving at the client
ws.onmessage = function (e) {
console.log("Message received: " + e.data);
//Close the socket once one message has arrived
ws.close();
}
}
//Start running the example
setup();
})();
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Websocket Echo Client</title>
<meta charset="utf-8"/>
</head>
<body>
<h2>Websocket Echo Client</h2>
<div id="output"></div>
<input type="file" id="fl"/>
<script src="websocket.js"></script>
</body>
</html>
Server code
switch (opcode) {
case opcodes.TEXT:
this.payload = payload.toString("utf8");
winston.log('info','Text:\r\n', this.payload);
break;
case opcodes.BINARY:
console.log('info','File:\r\n', payload.toString("utf8"));
As far as I know the payload you're receiving on the server side does not contain the meta data about the file. I believe the File object is treated as a normal Blob with some extra meta data and the ws.send is only handling it like a Blob (it has no special handling for File).
The meta data can be accessed using
document.querySelector('input[type="file"]').files[0].name
document.querySelector('input[type="file"]').files[0].size
document.querySelector('input[type="file"]').files[0].type
And then send separately.
I'm building a simple messaging server and it works perfect using the socket.broadcast.emit() however if you use the socket.broadcast.in(room).emit() it dose not connect up. I've include the server code and client code below.
server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Parse = require('parse').Parse;
var room;
app.get('/', function(req, res){
res.sendfile('index.html');
});
// When a new connection is launched
io.on('connection', function(socket){
console.log('user connected: '+socket.id);
//========== INIT connection =========
// once a client has connected, we expect to get a ping from them saying what room
// they want to join
socket.on('room', function(data) {
room = data;
socket.join(room);
console.log(' + User: '+socket.id+' - joined Room: ['+room+']');
console.log(' + User: '+socket.id+' - has Rooms: ['+socket.rooms+']');
// Display all sockets connected to room
inRoom(room);
});
//======== Delegates messages ========
socket.on('message_send', function(data){
var JSONdata = JSON.parse(data);
var room_l = JSONdata.chat_id;
var msg = JSONdata.message;
console.log('Room: ' + room_l + ' - Message: ' + msg);
// Send message
//io.emit('message_received', msg);
//socket.broadcast.emit('message_received', msg);
io.in('TZRfM7V5HH').emit('message_recieved', msg);
//io.to(room_l).emit('message_received', msg);
// Save message to parse
parseSAVE(data);
});
});
Client
<script>
var socket = io();
var msg = $('#m').val();
var room = 'TZRfM7V5HH';
$( document ).ready(function() {
socket.emit('room',room);
socket.emit('message_send', '{"chat_id":"'+room+'","message":"yoyoyo shits to hype"}');
});
$('form').submit(function(){
$msg = $('#m').val();
socket.emit('message_send', '{"chat_id":"'+room+'","message":"'+$msg+'"}');
$('#messages').append($('<li>').text($msg));
$('#m').val('');
return false;
});
socket.on('message_received', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
I have been playing around with this all week and I cant seem to figure out whats wrong with my implementation, any help or pointers would be greatly appreciated!
this my code from books "The Definitive Guide to HTML5 websocket".
....
<div id="output"></div>
<script>
function setup() {
output = document.getElementById("output");
ws = new WebSocket("ws://localhost:7777");
ws.onopen = function(e) {
log("Connected");
sendMessage("Hello Websocket!");
}
ws.onclose = function(e){
log("Disconnected: " + e.reason);
}
ws.onerror = function(e){
log("Error ");
}
ws.onmessage = function(e) {
log("Message received: " + e.data);
ws.close();
}
}
function sendMessage(msg){
ws.send(msg);
log("Message Sent");
}
function log(s){
var p = document.createElement("p");
p.style.wordWrap = "break-word";
p.textContent = s;
output.appendChild(p);
console.log(s);
}
setup();
</script>
but, when i'm running it in localhost.. the output just like this
Connected
Message Sent
and stop until that. i knew event onmessage is not firing, but i dont know why. what could possibly be the problem? thanks
onmessage will only fire when the server sends a message to the client, not when the client is sending a message to the server (which is what you're doing).
If your server is sending back a message and that isn't being picked up by your client, you're going to need to provide a bit more context (server implementation, etc).
I've a problem when opening the channel.
i've this on the server side:
def get(self):
user = users.get_current_user()
if not user:
self.redirect(users.create_login_url(self.request.uri))
return
channel_id=str(str(random.randint(0,1000)))
token = channel.create_channel(channel_id)
template_values = {
'token': token,
'me': user.user_id()
}
logger.debug("Token: %s user:%s %s %s" % (token,user.user_id(),user.nickname(),user.email()))
self.response.out.write(template.render('templates/index.html', template_values))
and this on the HTML (templates/index.html)
<html>
<head>
<script type="text/javascript" src="/_ah/channel/jsapi"></script>
</head>
<body>
{{ token }}
<script>alert("a0");
var token = {{ token }};
alert("a1");
var channel = new goog.appengine.Channel(token);
alert("a2");
var socket = channel.open();
alert("a3");
socket.onopen = function(){
alert("open");
};
socket.onmessage = function(m){
var data = $.parseJSON(m.data);
alert(data)
};
socket.onerror = function(err){
alert("Error => "+err.description);
};
socket.onclose = function(){
alert("channel closed");
};
</script>
</body>
</html>
I put alert to see if everything works, but a0 a1 a2 are raised, while a3 doesn't.
Where is the problem?
why channel.open() does not work?
PS: is there any way to trace these errors in javascript ? something more effective then guessing where is the error.
I had this same problem. It ran fine on local host, but did not work once I uploaded it. It appears that the tokens don't always start formatted correctly, and you need to trim them.
Thus the following alerts with "1", but then crashes:
if(user != null)
{
$.get("tutorial",{channelKey:userId} ,function(data) {alert(data); token = data;
alert(userId);
channel = new goog.appengine.Channel(data);
alert(1);
socket = channel.open();
alert(2);
socket.onopen = onOpened;
alert(3);
socket.onmessage = onMessage;
alert(4);
socket.onerror = onError;
alert(5);
socket.onclose = onClose;
alert(6);
});
If you change this to:
if(user != null)
{
$.get("tutorial",{channelKey:userId} ,function(data) {alert(data); token = data;
alert(userId);
channel = new goog.appengine.Channel(data.trim());
alert(1);
socket = channel.open();
alert(2);
socket.onopen = onOpened;
alert(3);
socket.onmessage = onMessage;
alert(4);
socket.onerror = onError;
alert(5);
socket.onclose = onClose;
alert(6);
});
However, it works perfectly and opens the channel!
For debugging use either Firebug or the Chrome debugger. You can log messages to the console by adding lines into your Javascript:
window.console.log("Message")
Double check that the value you get for 'token' is indeed the correct token.