I want to connect to my web socket that put on amazone instance with some ip. I can connect my web socket with some ip and port with google rest client app and its working very well.
Screen Shot :
But if i want to connect this with java script it can not connect. This is working fine before 2-3 month. i have not change and thing but its not working now.
If i want to connect with firefox it produce an error.
Here is my code :-
function init() {
var host = "ws://XX.XX.XXX.XXX:XXXX"; // SET THIS TO YOUR SERVER
try {
var socket = new WebSocket(host);
// alert('WebSocket - status ' + socket.readyState);
log('WebSocket - status ' + socket.readyState);
socket.onopen = function (msg) {
alert('open');
alert("Welcome - status " + this.readyState);
log("Welcome - status " + this.readyState);
if (this.readyState != 1)
{
reconnect();
}
};
socket.onmessage = function (msg) {
// alert("Received: " + msg.data);
log("Received: " + msg.data);
};
socket.onclose = function (msg) {
// alert("Disconnected - status " + this.readyState);
log("Disconnected - status " + this.readyState);
};
} catch (ex) {
alert(ex);
log(ex);
}
$("msg").focus();
}
This is alerting status 0 and error show in console :-
Firefox can't establish a connection to the server at ws://XX.XX.XXX.XXX:XXXX.
var socket = new WebSocket(host);
I'd try your code and for me is working just fine, I'd test it with this webpage: https://www.websocket.org/echo.html , maybe could be helpful for testing purposes. But also i found this question: websocket-rails, websocket handshake error , maybe also help.
However i'd just change the host in your code to this:"ws://echo.websocket.org", and everything works without problems.
Hope you find a solution and that this info was of any help. Here's your code that i used for the test:
function init() {
var host = "ws://echo.websocket.org";
try {
var socket = new WebSocket(host);
alert('WebSocket - status ' + socket.readyState);
socket.onopen = function (msg) {
alert('open');
alert("Welcome - status " + this.readyState);
if (this.readyState != 1)
{
reconnect();
}
};
socket.onmessage = function (msg) {
alert("Received: " + msg.data);
};
socket.onclose = function (msg) {
alert("Disconnected - status " + this.readyState);
};
} catch (ex) {
alert(ex);
}
$("msg").focus();
}
*Sorry for my bad english.
Related
My websocket works fine on localhost. But fails to run when I deploy my project on railway app
(which uses https)
It shows this error in the console log:
first error -
(index):382 Mixed Content: The page at 'https://supreme-key-production.up.railway.app/rooms/bangladesh_ott/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://supreme-key-production.up.railway.app/ws/bangladesh_ott/'. This request has been blocked; this endpoint must be available over WSS.
second error -
(index):382 Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.
at window.onload (https://supreme-key-production.up.railway.app/rooms/bangladesh_ott/:382:24)
This is in my script :
window.onload = function() {
const roomName = JSON.parse(document.getElementById('json-roomname').textContent);
const userName = JSON.parse(document.getElementById('json-username').textContent);
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/'
+ roomName
+ '/'
);
chatSocket.onmessage = function(e) {
console.log('onmessage')
const data = JSON.parse(e.data);
if (data.message) {
let html = '<div class="message">';
html += '<p class="messsage_username">' + data.username + '</p>';
html += '<p class="message_message">' + data.message + '</p></div>';
document.querySelector('#chat-messages').innerHTML += html;
} else {
alert('The message was empty!');
}
}
chatSocket.onclose = function(e) {
console.log('onclose')
}
//
document.querySelector('#chat-message-submit').onclick = function(e) {
e.preventDefault();
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message,
'username': userName,
'room': roomName
}));
messageInputDom.value = '';
return false;
}
}
Any solution for this?
i'm looking on what cases are these events is firing, i have implement it on these code
jQuery(document).ready(function() {
var chatChannel;
var chatClient;
var username;
var $input = $('#chat-input');
$.post("/tokens", function(data) {
username = data.username;
chatClient = new Twilio.Chat.Client(data.token);
chatClient.getSubscribedChannels().then(createOrJoinGeneralChannel);
});
function createOrJoinGeneralChannel() {
// Get the general chat channel, which is where all the messages are
// sent in this simple application
// print('Attempting to join "general" chat channel...');
var promise = chatClient.getChannelByUniqueName("#{params[:chat_channel]}");
promise.then(function(channel) {
chatChannel = channel;
console.log("#{params[:chat_channel]} is exist");
console.log(chatChannel);
setupChannel();
return channel.getMembers();
// $input.removeClass('.hidden')
})
.then(function(members){
members.forEach(function(member){
console.log('member', member);
member.on('userInfoUpdated', function(){
console.log('userInfoUpdated', member);
})
})
})
.catch(function() {
// If it doesn't exist, let's create it
console.log("creating #{params[:chat_channel]} channel");
chatClient.createChannel({
uniqueName: "#{params[:chat_channel]}",
friendlyName: 'General Chat Channel'
}).then(function(channel) {
console.log("Created #{params[:chat_channel]} channel:");
console.log(channel);
chatChannel = channel;
setupChannel();
});
});
}
function setupChannel() {
chatChannel.join().then(function(channel) {
printMessage(username + ' joined the chat.');
chatChannel.on('typingStarted', showTypingStarted);
chatChannel.on('typingEnded', hideTypingStarted);
chatChannel.on('memberJoined', notifyMemberJoined);
chatChannel.on('memberLeft', notifyMemberLeft);
chatChannel.on('memberUpdated', updateMemberMessageReadStatus);
});
chatChannel.on('messageAdded', function(message) {
printMessage(message.author + ": " + message.body);
});
}
function updateMemberMessageReadStatus(member){
console.log('memberUpdated');
console.log('member.lastConsumedMessageIndex', member.lastConsumedMessageIndex);
console.log('member.lastConsumptionTimestamp', member.lastConsumptionTimestamp);
}
function leaveCurrentChannel() {
if (chatChannel) {
chatChannel.leave().then(function (leftChannel) {
console.log('left ' + leftChannel.friendlyName);
leftChannel.removeListener('messageAdded', function(message) {
printMessage(message.author + ": " + message.body);
});
leftChannel.removeListener('typingStarted', showTypingStarted);
leftChannel.removeListener('typingEnded', hideTypingStarted);
leftChannel.removeListener('memberJoined', notifyMemberJoined);
leftChannel.removeListener('memberLeft', notifyMemberLeft);
leftChannel.removeListener('memberUpdated', updateMemberMessageReadStatus);
});
}
}
function showTypingStarted(member) {
console.log('somebody is typing');
$('#is_typing').html(member.identity + ' is typing...');
}
function hideTypingStarted(member) {
$('#is_typing').html('');
}
function notifyMemberJoined(member) {
console.log('notifyMemberJoined');
printMessage(member.identity + ' joined the channel');
}
function notifyMemberLeft(member) {
console.log('notifyMemberLeft');
printMessage(member.identity + ' left the channel');
}
$input.on('keydown', function(e) {
if (e.keyCode == 13) {
chatChannel.sendMessage($input.val());
$input.val('');
} else {
//console.log('typing');
chatChannel.typing();
}
});
window.addEventListener("beforeunload", function (e) {
// var confirmationMessage = "\o/";
(e || window.event).returnValue = leaveCurrentChannel(); //Gecko + IE
return leaveCurrentChannel(); //Webkit, Safari, Chrome
});
});
and i've take alook to the console to see if my
console.log('userInfoUpdated', member);
or these guys
console.log('memberUpdated');
console.log('member.lastConsumedMessageIndex', member.lastConsumedMessageIndex);
console.log('member.lastConsumptionTimestamp', member.lastConsumptionTimestamp);
and they are never fired, during my test on the chat events, and i'm confused on how exactly i'm going to display how my users online or the status of a message is read or unread
so please enlighten me on the case, thank you
Twilio developer evangelist here.
According to the JS docs for the latest version of Twilio Chat, the event you need to listen for on members is just called 'updated'. So, listening for 'userInfoUpdated' won't work.
I would also recommend that within this code:
chatChannel.join().then(function(channel) {
//...
chatChannel.on('memberUpdated', updateMemberMessageReadStatus);
//...
})
you use the channel passed to the callback, rather than the original chatChannel object. Like this:
chatChannel.join().then(function(channel) {
//...
channel.on('memberUpdated', updateMemberMessageReadStatus);
//...
})
I don't know if this will fix the issue, but I can't think of anything else right now.
I'm having trouble while developing chat-like feature to my socket server.
First let me give you a little bit of my code:
document.conn = new ab.Session('ws://127.0.0.1:8090',
function () {
console.log('AB:Connected!');
conn.subscribe('room_1', function (topic, data) {
console.log('New message published to room "' + topic + '" : ' + data.content + ' by:' );
console.log(data);
});
},
function () {
console.warn('WebSocket connection closed');
},
{'skipSubprotocolCheck': true}
);
Currently it's attached to document just to try it out, the error I'm getting is as follows:
"Session not open"
I'm a bit confused about this error and it's origin, should I somehow define the connection?
do you start your socket server through cmd.exe ?
you need to use this command to start the server:
php c://wamp64/www/yourproject/bin/push-server.php
I need to detect whether an specific .js file was served in a http response and additionally, check the domain it came from, like this:
I need to automatically detect the lack of the js file and email the incidence
I tried Net::Http, rest-client, mechanize and a lot of gems, they just return the html header. It seems I need to monitor http traffic with tools like PhantomJS and checking for the file, but is there any rubyesque way of doing this?
Thanks in advance
I ended with the phantomjs approach. A ruby script iterate over a database table and then calls this phantomjs script for each record representing an URL
This is the phantomjs script
var page = require('webpage').create(),
system = require('system'),
address,
isScript = false;
var fs = require('fs');
// main
analizePage(system.args[1]);
//open page.
//onResourceRequested event, compares domain of each one with 'my.domain.net'
//append to a log file: -1 for failed url, 1 for script presence, 0 for no script presence
function analizePage(address){
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address ' + address);
fileWriter(-1, address);
}
else
{
if (!isScript){
fileWriter(0, address);
}
else
{
fileWriter(1, address);
}
console.log('Has script: ' + isScript);
}
phantom.exit(0);
});
page.onResourceRequested = function (req) {
try {
var link = document.createElement('a');
link.setAttribute('href', req.url); //extract asset's domain from URL
if (link.hostname == 'my.domain.net') {
isScript = true;
}
} catch(e) {
console.log("PAGE OPEN ERROR: " + e);
}
};
}
function fileWriter(type, line){
try {
fs.write("scriptlog.csv", type + ',' + line + ',' + Date.now() + ',' + system.args[2] + '\n', 'a');
} catch(e) {
console.log("FILE ERROR: " + e);
}
}
I am working phonegap + rest webservice. The service given below is working gud with web application test. the image file was uploaded in the local webserver. But same service is not working in phonegap. Included both codes here.
RestWebService
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("image") InputStream uploadedInputStream,
#FormDataParam("image") FormDataContentDisposition fileDetail) {
System.out.println("entered");
//some logic .. this method is working good using webapplication ... i tested using html page
}
Phonegap code
function myDetails()
{
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imgByte.substr(imgByte.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var ft = new FileTransfer();
ft.upload(imgByte, IMGURL, win, fail, options);
alert("finished calling upload");
}
function win(r) {
alert("success");
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
New some guidance
Log cat error :
04-18 18:30:31.621: E/FileTransfer(9459): {"target":"http:\/\/10.1.6.88:8080\/TodaysAdminAds\/resources\/service\/vendor\/vendorregistration","source":"\/9j\/4AAQSkZJRgABAQAAAQ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