i am trying to send a packet to the client when it connects.
for server side i have used Socket.io with OSGI and Karaf.
and i am sending it as
server.addConnectListener(new ConnectListener() {
#Override
public void onConnect(SocketIOClient client) {
log.info("A new client has connected -> {}", client.getSessionId());
int count = 1;
boolean count1 = true;
StringBuffer builder = new StringBuffer();
for(int i=0; i < 5; i++) { builder.append("A"); }
Packet packet = new Packet(PacketType.EVENT);
packet.setName("trader");
ArrayList arr = new ArrayList();
arr.add(builder.toString());
packet.setData(arr);
System.out.println("sending data " + arr);
client.send(packet);
}
});
and the client i am accessing it as
<script src='http://code.jquery.com/jquery-1.7.2.min.js'></script>
<script src='https://cdn.socket.io/socket.io-1.1.0.js'></script>
<script>
var socket = io.connect('ws://localhost:8807');
socket.on('connect', function(data) {
debugger;
console.log("connected");
});
socket.on('time', function(data) {
console.log(data);
$('#messages').append('<li>' + data.time + '</li>');
});
socket.on('trader', function(data){
console.log("recieving data");
$('#messages').append('<li>' + data + '</li>');
});
socket.on('Message', function(data){
console.log("recieving data");
$('#messages').append('<li>' + data + '</li>');
});
socket.on('error', function(data) {
debugger;
console.error(arguments)
});
</script>
i am getting the error as
message: "xhr poll error", type : type: "TransportError"
Related
Hey Guys,
I have a problem to show my picture on my Page.
I dont know how to set the right path to show my picture.
I use socket.io and express. The Page is running on a Localhost Server
this is my code to show the picture but it doesnt works.
img src="uploads/images.png"
On the server-side i did this "app.use(express.static('public'));" to make it public. But it doesnt work, can someone help me ?
What is the right path?
My Folder structure is this
Folder structure
Server-side:
var app = require('express')();
var express = require('express');
var upload = require('express-fileupload');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var multer = require('multer');
var fs = require('fs');
app.use(upload());
app.use(express.static('public'));
var users = {};
var allUsers = [];
function actualTime(){
var d = new Date();
return d.toLocaleTimeString();}
http.listen(3000, function(){
console.log('listening on *:3000');
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
app.post('/upload',function(req,res){
console.log(req.files);
if(req.files.upfile){
var file = req.files.upfile,
name = file.name,
type = file.mimetype;
var uploadpath = __dirname + '/uploads/' + name;
file.mv(uploadpath,function(err){
if(err){
console.log("File Upload Failed",name,err);
res.send("Error Occured!")
}
else {
console.log("File Uploaded",name);
console.log("guckmal");
io.emit('file', name);
res.send('sasa');
}
});
}
else {
res.send("No File selected !");
res.end();
};
})
socket.on('username', function(data,callback){
if(data in users || data.length<=2){
callback(false);
}else{
callback(true);
socket.nickname = data;
users[socket.nickname] = socket;
// to get a message for all users who are not in the priavte chat
allUsers.push(""+socket.nickname);
for(var test=0; test<allUsers.length;test++){
console.log(allUsers[test]);
users[allUsers[test]].emit('usernames', {list:Object.keys(users), nick: allUsers[test]});
}
io.emit('chat message',{msg:"joined the Chatroom", nick:socket.nickname, time:actualTime()});
}
});
socket.on('chat message', function(data, callback){
console.log(socket.nickname);
console.log('User: ' + socket.nickname + ' message: ' + data);
var msg = data.trim();
if(msg.substr(0,3)=== '/w '){
console.log("private chat");
msg= msg.substr(3);
var temp = msg.indexOf(' ');
if(temp !== -1){
console.log("private chat stap 2");
var name = msg.substring(0,temp);
var msg = msg.substring(temp+1);
if(name in users){
console.log("private chat stap 3");
users[name].emit('private chat', {msg:msg, nick:socket.nickname, time:actualTime()});
for(var i=0; i<allUsers.length;i++){
if((name !==allUsers[i])){
if(allUsers[i] !== socket.nickname){
users[allUsers[i]].emit('private chat',{msg:"private message was send from "+socket.nickname+" to "+name, nick:socket.nickname, time:actualTime()});
}else{
users[socket.nickname].emit('private chat',{msg:"you send a private messgae to "+name, nick:"chat", time:actualTime()});
}
}
}
}else{
callback(' user name doesnt exist');
}
}else{
callback('Error! Please enter a message');
}
}else{
io.emit('chat message', {msg:msg, nick:socket.nickname, time:actualTime()});
}
});
socket.on('disconnect', function(data){
delete users[socket.nickname];
io.emit('chat message',{msg:"leaved the Chatroom", nick:socket.nickname, time:actualTime()});
io.sockets.emit('usernames', {list:Object.keys(users)});
});
});
Client-side:
$(function () {
var socket = io();
$('#loginForm').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('username', $('#u').val(), function(data,callback){
if(data){
$('#nickWrap').hide();
$('#contentWrap').show();
}else if(($('#u').val()).length<=2){
document.getElementById("u").value="";
document.getElementById("u").placeholder ="Sorry but Username length is less then three :(";
}else{
document.getElementById("u").value="";
document.getElementById("u").placeholder ="Sorry but Username already taken :(";
}
});
});
$('#chatForm').submit(function(e){
e.preventDefault(); // prevents page reloading
if(privateUsers.length>0){
for(var i=0;i<privateUsers.length;i++){
socket.emit('chat message','/w '+ privateUsers[i] +' '+ $('#m').val(), function(data){
// add stuff later
$('#messages').append($('<li>').text(data.time + " " + data.nick +': '+ data.msg ));
});
}
}else{
socket.emit('chat message', $('#m').val(), function(data){
// add stuff later
$('#messages').append($('<li>').text(data.time + " " + data.nick+': '+ data.msg ));
});
}
$('#m').val('');
return false;
});
socket.on('chat message', function(data){
$('#messages').append($('<li>').text(data.time + " " + data.nick +': '+ data.msg ));
});
socket.on('file', function(data){
var img = document.getElementById('bild');
images.push[data];
var name = data;
console.log(name);
$('#messages').append('<li><img src="uploads/images.png" />'+ '</li>');
img.setAttribute('src','data:image/jpeg;base64,' + window.btoa(images));
});
socket.on('private chat', function(data){
$('#messages').append($('<li>').text(data.time + " " + data.nick +': '+ data.msg ));
});
socket.on('usernames', function(socket, data){
console.log("2222222222");
// to get a massage for all users who are not in the priavte chat
console.log(socket.nick);
socketName = socket.nick;
});
socket.on('usernames', function(data){
document.getElementById("userList").innerHTML = "";
var temp;
var indexTemp;
var me= "";
var sortData = [];
for(var i=0;i<data.list.length;i++){
if(data.nick === data.list[i]){
indexTemp = i;
/* temp = data.list[i];
indexTemp =i;
data.list[i]= "Ich";*/
me ="My Name: ";
}
}
// sort list
sortData.push(data.list[indexTemp]);
for(var l=0; l<data.list.length;l++){
if(indexTemp !=l){
sortData.push(data.list[l]);
}
}
for(var i =0; i<sortData.length;i++){
if(i==0){
$('#userList').append('<li style="list-style:none "><buttonid="'+sortData[i]+'" onclick='+'"addUsers()"'+
' style="width: 100%; background: rgb(130, 224, 255); border: none; padding:10%; margin-bottom:2%; "'+'>'+"My Name: "+ sortData[i]
+'</button></li>');
//data.list[i]= temp;
}else{
$('#userList').append('<li style="list-style:none "><button id="'+sortData[i]+'" onclick='+'"addUsers(\''+sortData[i]+'\')"'+
' style="width: 100%; background: rgb(130, 224, 255); border: none; padding:10%; margin-bottom:2%; "'+'>'+ sortData[i]
+'</button></li>');
}
}
// }
});
});
function addUsers(name){
if(privateUsers.length==0){
console.log("erstes objekt");
document.getElementById(name).style.background = "rgb(1, 254, 185)";
privateUsers.push(name);
}else{
for(var i=0;i<privateUsers.length;i++){
if(name==privateUsers[i]){
console.log("gel�scht");
document.getElementById(name).style.background = "rgb(130, 224, 255)";
privateUsers.splice(i,1);
return;
}
}
console.log("drinnen");
document.getElementById(name).style.background = "rgb(1, 254, 185)";
privateUsers.push(name);
}
}
I have 20 data packet in the client and I am pushing one by one to the server via Ajax post. Each call take approximately one minute to yield the response. Is there any way to make few of these requests run parallel.
I have used Jquery promise. However, still the request waiting for the prior one to get completed.
var dataPackets=[{"Data1"},{"Data2"},{"Data3"},{"Data4"},{"Data5"},
{"Data6"},{"Data7"},{"Data8"},{"Data9"},{"Data10"},
{"Data11"},{"Data12"},{"Data13"},{"Data14"},{"Data15"},{"Data16"},
{"Data17"},{"Data18"},{"Data19"},{"Data20"}];
$(dataPackets).each(function(indx, request) {
var req = JSON.stringify(request);
setTimeout({
$.Ajax({
url: "sample/sampleaction",
data: req,
success: function(data) {
UpdateSuccessResponse(data);
}
});
}, 500);
});
The when...done construct in jQuery runs ops in parallel..
$.when(request1(), request2(), request3(),...)
.done(function(data1, data2, data3) {});
Here's an example:
http://flummox-engineering.blogspot.com/2015/12/making-your-jquery-ajax-calls-parallel.html
$.when.apply($, functionArray) allows you to place an array of functions that can be run in parallel. This function array can be dynamically created. In fact, I'm doing this to export a web page to PDF based on items checked in a radio button list.
Here I create an empty array, var functionArray = []; then based on selected items I push a function on to the array f = createPDF(checkedItems[i].value)
$(document).ready(function () {
});
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function exportPDFCollection() {
var f = null;
var x = 0;
var checkedItems = $("input:checked");
var count = checkedItems.length;
var reportList = $(checkedItems).map(
function () {
return $(this).next("label").text();
})
.get().join(",");
var functionArray = [];
var pdf = null;
for (var i = 0; i < count; i++) {
f = createPDF(checkedItems[i].value)
.done(function () {
pdf = checkedItems[x++].value;
alert('PDF => ' + pdf + ' created.');
})
.fail(function (jqxhr, errorText, errorThrown) {
alert('ajax call failed');
});
functionArray.push(f);
}
$.when.apply($, functionArray)
.done(function () {
$.get("http://yourserver/ExportPage.aspx",{reports: reportList})
.done(function () {
alert('PDF merge complete.');
})
.fail(function (jqxhr, errorText, errorThrown) {
alert('PDF merge failed. Please try again.');
});
return true;
});
}
function createPDF(webPage) {
return $.get(webPage);
}
I'm using sockjs-0.3.4.
Before change page structure, it worked normally.
However after changing some stuff. abrubtly ws.onmessage function is beginning not to called.
I checked the connection with server by looking into devtools.
It looks like getting data from the server.
Please help me to know what's the point to check out.
enter image description here
var statusWatcher = {
curPage:"",
ws: null,
wsBaseUrl :null,
uid: null,
init : function(url ){
if(statusWatcher.ws != null) return;
console.log(statusWatcher.ws);
console.log("wsBaseUrl:"+url)
statusWatcher.wsBaseUrl = url;
var browserSupport = ("WebSocket" in window)? true: false;
if(browserSupport){
statusWatcher.start();
}else{
console.log("WebSocket is Not supported by your Web Browser!");
}
//log.eventHandler(1);
},
start : function(){
baseWsURL = statusWatcher.wsBaseUrl+"/statusCheck?&uid="+statusWatcher.uid;
console.log("web socket baseurl:"+baseWsURL);
try{
statusWatcher.ws = new WebSocket(baseWsURL);
} catch (e){
console.log(e);
}
statusWatcher.ws.onopen = function() {
console.log("web socket Opened! ");
};
statusWatcher.ws.onclose = function() {
console.log("web syslog socket Closed! ");
};
statusWatcher.ws = function(err) {
console.log("web syslog socket Error: " + err);
};
statusWatcher.ws.onmessage = function(evt) {
console.log("get message...");
//console.log("page:"+curPage);
var data = evt.data;
console.log(data);
var msg;
if(curPage =="main") return;
var e = JSON.parse(data);
if(e.status =="COMPLETE"){
$("#" + e.groupId).text("complete");
$("#" + e.groupId).removeClass('run error');
$("#" + e.groupId).addClass('complete');
statusWatcher.updateScoreState(e.groupId, "COMPLETE", e.topRplRate,e.topKwdRate);
}else if(e.status == "ERROR"){
$("#" + e.groupId).text("error");
$("#" + e.groupId).removeClass('run complete');
$("#" + e.groupId).addClass('error');
statusWatcher.updateScoreState(e.groupId, "ERROR");
}else{
$("#" + e.groupId).html("running("+e.progress+"/"+e.total+")");
$("#" + e.groupId).removeClass('error complete');
$("#" + e.groupId).addClass('run');
statusWatcher.updateScoreState(e.groupId, "RUNNING");
}
};
},
}
}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<script src="<c:url value="js/fileuploadMain/statusWatcher.js"/>"></script>
</head>
<body>
<!--header-->
<c:import url="/WEB-INF/jsp/fileupload/header.jsp" />
<!--contents-->
<div class="contents">
<div class="container" id="container">
</div>
</div>
<script>
$(document).ready(function() {
var nice = $("html").niceScroll(); // The document page (body)
$(".select-items").niceScroll({
zindex: "auto",boxzoom:false
});
$("#container").load("group.do");
calaendar.init();
var wsBaseUrl = "ws://"+document.location.host+"<c:out value="${pageContext.request.contextPath}"/>";
statusWatcher.init(wsBaseUrl);
});
</script>
</body>
</html>
statusWatcher.ws = function(err) {
console.log("web syslog socket Error: " + err);
};
I changed upper source code to the next.. Maybe I remove the function name mistakenly..
statusWatcher.ws.onerror = function(err) {
console.log("web syslog socket Error: " + err);
};
Hi I'm developing a chat application using nodejs I'm new to node so I'm not very well familiar on its capabilities... I have made my application store its chat messages on mysql database only but I need to also display the past message and current one of a user here is the index.js
var mysql = require('mysql');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var validator;
var connection = mysql.createConnection({ // setup the connection
host : "localhost",
user : "root",
password: "",
})
function getStdout(command, args, fn) {
var childProcess = require('child_process').spawn(command, args);
var output = '';
childProcess.stdout.setEncoding('utf8');
childProcess.stdout.on('data', function(data) {
output += data;
});
childProcess.on('close', function() {
fn(output);
});
}
app.use('/assets', require('express').static(__dirname + '/assets'));
app.use('/temp', require('express').static(__dirname + '/temp'));
app.get('/', function(req, res){
//res.sendfile(__dirname + '/' +validator);
res.send(validator);
});
//you should have only one io.on('connection')
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
var myMsg= msg; // obtain the incoming msg
var strQuery = "INSERT INTO chat_storage(chat) VALUES(?)"; // your SQL string
connection.query("use schat"); // select the db
connection.query( strQuery, myMsg, function(err, rows){
if(err) {
// handle errors
} else {
io.emit('chat message', msg);
// message received
}
});
});
});
getStdout('php', ['message.php'], function(output) {
validator = output;
//start your server after you get an output
http.listen(3000, function(){
console.log(validator);
});
});
now here is the page for loading the chat messages
<?php startblock('script') ?>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "localhost:3000/includes/message/store_chat.php",
type: "POST",
dataType: "html",
success: function (result) {
$("#messages").html(result);
}
});
});
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
<?php endblock(); ?>
My idea was to the chat messages once the page loads I was trying to achieve it using ajax as you can see on the script that I have provided.. but it was no good didnt work at all Please help me
Couple of suggestions:
1) Store all of your messages in-memory ( unless you see this growing to several MB of data ) so that you can catch up any new client quickly.
2) Use socket.io to send the chat messages that have been stored rather than an AJAX call.
I've also included SequelizeJS instead of raw MySQL - It has a much cleaner raw query model and allows you to transition into a DAO model of sorts if you want to.
app.js
// Highly suggest replacing raw mysql with SequelizeJS - http://sequelizejs.com/
var Sequelize = require('sequelize'),
app = require('express')(),
http = require('http').Server(app),
io = require('socket.io')(http);
var validator;
var messages = [];
var sequelize = new Sequelize('schat', 'root', '');
app.use('/assets', require('express').static(__dirname + '/assets'));
app.use('/temp', require('express').static(__dirname + '/temp'));
app.get('/', function(req, res){
res.send(validator);
});
io.on('connection', function(socket){
// Send all previously sent messages
for( i in messages ) {
socket.emit('chat message', messages[i]);
}
socket.on('chat message', function(msg){
console.log('message: ' + msg);
// Push the message into the in-memory array.
messages.push(msg);
// Storage the message for when the application is restarted.
sequelize.query('INSERT INTO chat_storage(chat) VALUES("'+msg'")').success(function() {
// Insert was successful.
}).error(function (err) {
// Error inserting message
});
// Send the message to everyone
socket.broadcast.emit('chat message', msg);
});
});
function getStdout(command, args, fn) {
var childProcess = require('child_process').spawn(command, args);
var output = '';
childProcess.stdout.setEncoding('utf8');
childProcess.stdout.on('data', function(data) {
output += data;
});
childProcess.on('close', function() {
fn(output);
});
}
// Load Messages
sequelize.query('SELECT chat FROM chat_storage').success(function (rows) {
for( i in rows ) {
messages.push(rows[i].chat);
}
getStdout('php', ['message.php'], function(output) {
validator = output;
http.listen(3000, function(){
// Start server.
});
});
}).error(function (err) {
// Error!
});
php include
<?php startblock('script') ?>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#messages').append($('li').text($('#m').val()));
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
<?php endblock(); ?>
My node app posts an object (consisting of data collected in a form on the client) to Salesforce via their API. On receiving a success or error message, I would like to send it to the client-side, then display it. Socket.io seemed like the tool for this in my simple node/express3 app, but beyond the simple demo I'm not able to get data to pass between my server and my client.
My relevant server side code:
var express = require('express');
var port = 5432;
var app = module.exports = express();
var server = require('http').createServer(app);
var nforce = require('nforce');
var org = nforce.createConnection({
clientId: 'MY_CLIENT_ID',
clientSecret: 'MY_CLIENT_SECRET',
redirectUri: 'http://localhost:5432/oauth/_callback'
});
var io = require('socket.io').listen(server);
// here I authenticate with Salesforce, this works fine
app.post('/salesforce', function(req, res){
var lead = nforce.createSObject('Lead');
// here I construct the lead object, which also works fine
org.insert(lead, oauth, function(err, res) {
if (err === null) {
console.log(res);
leadSuccessMessage(res);
}
else {
console.log(err);
var error = {
errorCode: err.errorCode,
statusCode: err.statusCode,
messageBody: err.messageBody
};
console.log(error);
leadErrorMessage(error);
}
});
}
function leadSuccessMessage(res) {
var resp = res;
console.log('called success message from server');
io.sockets.on('connection', function (socket) {
socket.emit('sfRes', resp);
socket.on('thanks', function (data) {
console.log(data);
});
});
}
function leadErrorMessage(error) {
var err = error;
console.log('called error message from server');
io.sockets.on('connection', function (socket) {
console.log("socket is: " + socket);
socket.emit('sfRes', err);
socket.on('thanks', function (data) {
console.log(data);
});
});
}
And my relevant client side scripts:
<script src="/socket.io/socket.io.js"></script>
<script>
current.page = document.URL;
console.log("current page is: " + current.page);
var socket = io.connect(current.page);
socket.on('sfRes', function (data) {
console.log("client received: " + data);
fst.showLeadStatus(data);
socket.emit('thanks', {message: "received server feedback"});
});
</script>
When I post the form containing valid data using a spicy little AJAX call:
postToSF: function(){
$('#submitLead').on('click', function(e){
e.preventDefault();
var formData = $('#lead_form').serialize();
$.ajax({
type: 'POST',
url: '/salesforce',
data: formData,
success: function(){
fst.log('success!');
},
error: function(xhr, ajaxOptions, thrownError){
console.error(xhr.status); // 0
console.error(thrownError);
}
});
});
}
All I get are tears, and these in the server-side console:
// the result of `console.log(res)`
{ id: '00Qa000001FZfhKEAT', success: true, errors: [] }
// and proof that `leadSuccessMessage()` got called
called success message from server
Instead of calling this function from a client-side object as it's supposed to:
showLeadStatus: function(response){
if (response.success) {
fst.log("showing lead status as: " + response);
$('#leadStatus').addClass('success').removeClass('error').fadeIn().delay(4000).fadeOut();
}
else {
fst.log("showing lead status as: " + response);
$('#leadStatus').text(response.messageBody).addClass('error').removeClass('success').fadeIn().delay('4000').fadeOut();
}
$('#startOver').click();
}
Which works fine if I call it in the console passing it the data the server is supposed to be socketing over:
// this works, gosh darn it
fst.showLeadStatus({ id: '00Qa000001FZfhKEAT', success: true, errors: [] });
The Salesforce post error case doesn't surface anything to the client either. And there are no errors in the client or server console to contend with.
I'm stumped. Please help!
I would do something like this -
var mysocket = null;
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
mysocket = socket;
socket.on('thanks', function (data) {
console.log(data);
});
});
app.post('/salesforce', function(req, res){
....
....
})
function leadSuccessMessage(res) {
var resp = res;
console.log('called success message from server');
if(mysocket)
mysocket.emit('sfRes', resp);
}
function leadErrorMessage(error) {
var err = error;
console.log('called error message from server');
if(mysocket)
mysocket.emit('sfRes', err);
}