I have my website for using jsp. I wanted to use webcsocket to impement chatting. I tried a simple example to test whether it works or not. My code for server end point is given below:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package endpoint;
/**
*
* #author yashs
*/
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class MyServerEndPoint {
#OnMessage
public String echo(String message) {
System.out.println("echo:" + message);
return "Echoing " + message;
}
}
The client side code is given below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login V1</title>
<script type="text/javascript">
function debug(s) {
var d = document.getElementById("debug");
d.innerHTML = d.innerHTML + "<br/>" + s;
}
function sendMessage(msg) {
if (!("WebSocket" in window)) {
debug("Your browser does not support WebSocket.");
return;
}
var uri = "ws://" + document.location.host
+ document.location.pathname + "echo";
var ws = new WebSocket(uri);
ws.onopen = function () {
debug("Connected.");
ws.send("Hello");
};
ws.onmessage = function (evt) {
debug("Received: " + evt.data);
};
ws.onclose = function () {
debug("Connection closed.");
};
}
</script>
</head>
<body>
Send Message
<div id="debug"></div>
</body>
</html>
the name of my project is handiazza
the client side page is the index.html page which is automatically created when you create a new web application in netbeans.
So when ever I run my app using
localhost:8084/handiazza/
then it works fine. But if I copy the same client side code and paste into a new file then it does not work. I saw many examples on google but all the examples have same mechanism of using localhost and the app name
Related
const tmi = require('tmi.js');
// Define configuration options
var x = "asdfasdf"
const opts = {
identity: {
username: 'username',
password: 'password'
},
channels: [
"rabeya74"
]
};
// Create a client with our options
const client = new tmi.client(opts);
// Register our event handlers (defined below)
client.on('message', onMessageHandler);
client.on('connected', onConnectedHandler);
// Connect to Twitch:
client.connect();
// Called every time a message comes in
function onMessageHandler(target, context, msg, self) {
if (self) {
return;
} // Ignore messages from the bot
// Remove whitespace from chat message
const commandName = msg.trim();
// If the command is known, let's execute it
if (commandName === '!dice') {
const num = rollDice();
client.say(target, `You rolled a ${num}`);
document.body.innerHTML = x;
console.log(`* Executed ${commandName} command`);
document.body.innerHTML = `You rolled a ${num}`;
window.onload = function() {
document.getElementById("display").innerHTML = "hello";
}
document.getElementById("display").innerHTML = "hello";
} else {
console.log(`* Unknown command ${commandName}`);
}
}
// Function called when the "dice" command is issued
function rollDice() {
const sides = 6;
return Math.floor(Math.random() * sides) + 1;
}
// Called every time the bot connects to Twitch chat
function onConnectedHandler(addr, port) {
console.log(`* Connected to ${addr}:${port}`);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="bot.js"></script>
<div id="display"></div>
</body>
</html>
I'm trying to make a small twitch javascript app that updates the HTML file when I roll a dice. I tried every version of the document.body.innerHTML file but it simply does not want to update. Is it because it's in a function? It seems to just not show anything.
You can't use require() in the browser. This code produces an error because require is undefined. Try adding a <script src="tmi.js"></script> in your <head> element.
I found similar threads but unfortunately didn't help resolve my issue so posting a new thread
I am trying to consume the linked API through localhost. The error I am getting is:
Uncaught Error: You must specify a valid JavaScript API Domain as part of this key's configuration.
Under Javascript Settings, Valid SDK Domains I added
http://127.0.0.1
http://127.0.0.1:8704
http://localhost
http://localhost:8704
http://localhost
I tried adding in https as well but still I am facing the same error.
I tried creating a ASP.NET project in Visual studio and tried running my html file with the associated port number which also I added in valid SDK domain, still the same issue.
My code is below:
<html>
<head>
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: [MY KEY] //Client ID
onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load
authorize: true
</script>
</head>
<script type="text/javascript">
function OnLinkedInFrameworkLoad() {
console.log('OnLinkedInFrameworkLoad');
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
console.log('OnLinkedInAuth');
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles) {
console.log('ShowProfileData' + profiles);
var member = profiles.values[0];
var id = member.id;
var firstName = member.firstName;
var lastName = member.lastName;
var photo = member.pictureUrl;
var headline = member.headline;
//use information captured above
var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: "
+ lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline
+ "<p/>"
document.getElementById('profiles').innerHTML = stringToBind;
}
</script>
<body>
<div id="profiles"></div>
</body>
</html>
While building a chat application in Django, I used embedded javascript and it worked. But, if I write the same code in external javascript then the WebSocket gets closed. I have checked all the links and static file path. The script is loaded completely but the WebSockets gets closed after they open.
Here's the tutorial from Official Django Channels website, and that javascript is working in embedded form only not in an external script.
And, here's my Github repo where I've implemented Websockets.
How can I write JS code in external script instead of embedded? I've Googled but found no help and even this question hasn't been answered yet.
Here's the code I'm talking about and the websockets won't work if defined externally:
<!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br/>
<input id="chat-message-input" type="text" size="100"/><br/>
<input id="chat-message-submit" type="button" value="Send"/>
</body>
<script>
var roomName = {{ room_name_json }};
var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/');
chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data['message'];
document.querySelector('#chat-log').value += (message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
var messageInputDom = document.querySelector('#chat-message-input');
var message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
};
</script>
</html>
I am trying to set up a basic WSS websockets server. This is my minimal HTML (with the embedded javascript):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body style="background-color:white">
<h1>Test of WSS server</h1>
<p>Status: <span id=status"></span></p>
Click to send message
<script src="/newjs/jquery-2.1.1.js"></script>
<script>
var connection;
$(document).ready(function () {
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
alert("browser says no");
console.log("Browser does not supports websockets");
return;
}
setupConnection();
});
function message() {
var msg = "Test Message";
connection.send(msg);
}
function setupConnection() {
connection = new WebSocket('wss://www.example.com:14000');
connection.onerror = function(error) {
console.log('onerror fired');
};
connection.onopen = function(event) {
$("#status").html("Open");
};
connection.onmessage = function (message) {
alert(message.data);
};
}
setInterval(function() {
if (connection.readyState !== 1) {
setupConnection();
}
}, 5000);
</script>
</body>
</html>
The following is the JS server run by nodejs:
var fs=require("fs");
var ws_cfg = {
ssl: true,
port: 14000,
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
ca_cert: '/httpd/conf/ssl.crt/gd_bundle-g2-g1.crt'
};
var processRequest = function(req, res) {
console.log("Request received.")
};
var httpServ = require('https');
var app = null;
app = httpServ.createServer({
key: fs.readFileSync(ws_cfg.ssl_key),
cert: fs.readFileSync(ws_cfg.ssl_cert),
ca: fs.readFileSync(ws_cfg.ca_cert),
},processRequest).listen(ws_cfg.port);
var WebSocketServer = require('ws').Server, ws_server = new WebSocketServer( {server: app});
ws_server.on('open',function(request) {
console.log("opening");
});
ws_server.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
if (request.origin!='https://www.example.com') {
console.log("rejecting request from " + request.origin + " as not coming from our web site");
return;
}
var connection = request.accept(null, request.origin);
connection.on('message', function(message) {
console.log("Got a message");
});
});
I fire up the server with node then load the web page in my browser (using either FF or Chrome). Using the developer tools I see that the connection appears to be made. On the server side I see the established connection using netstat. I also put an alert() in the browser side in the onopen() function and it fired.
The problem is that no console log output is produced. When connection.send(mag) is executed the on("message" event never appears to fire on the server. I'm at a loss here. I had this working as an http:// websocket server but this is my first attempt at wss:. I would appreciate any insight.
Notes:
The sever name is not example.com although that is what I show in my code.
The firewall is allowing anyone to connect on port 14000 using TCP protocol.
The cert is a working wildcard cert for the web site.
Finally figured out what it was after ignoring it for a month or so. It had to do with the symbolic link (/httpd) defined for the SSL files as in:
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
They had to be changed to:
ssl_key: '/usr/local/apache2/conf/ssl.key/my.key',
ssl_cert: '/usr/local/apache2/conf/ssl.crt/my.crt',
Who knew that symbolic links were frowned upon? Well, now we all do.
Let's say I've the following sample code (JavaScript):
// Client A
var conn = new XSockets.WebSocket([wsUri]);
conn.on(XSockets.Events.open, function (clientInfo) {
conn.publish("some:channel", { text: "hello world" });
});
// Client B (subscriber)
var conn = new XSockets.WebSocket([wsUri]);
conn.on(XSockets.Events.open, function (clientInfo) {
conn.on("some:channel", function(message) {
// Subscription receives no message!
});
});
Client B never receives a message. Note that this is a sample code. You might think that I don't receive the message because Client B got connected after Client A sent the message, but in the actual code I'm publishing messages after both sockets are opened.
The server-side XSocketsController is working because I'm using it for server-sent notifications.
What am I doing wrong? Thank you in advance!
It looks like you have mixed up the pub/sub with the rpc, but I cant tell for sure if you do not post the server side code as well.
But what version are you using? 3.0.6 or 4.0?
Once I know the version and have the server side code I will edit this answer and add a working sample.
EDIT (added sample for 3.0.6):
Just wrote a very simple chat with pub/sub.
Controller
using XSockets.Core.Common.Socket.Event.Interface;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
namespace Demo
{
public class SampleController : XSocketController
{
/// <summary>
/// By overriding the onmessage method we get pub/sub
/// </summary>
/// <param name="textArgs"></param>
public override void OnMessage(ITextArgs textArgs)
{
//Will publish to all client that subscribes to the value of textArgs.#event
this.SendToAll(textArgs);
}
}
}
HTML/JavaScript
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/XSockets.latest.min.js"></script>
<script>
var conn;
$(function() {
conn = new XSockets.WebSocket('ws://127.0.0.1:4502/Sample');
conn.onopen = function(ci) {
console.log('open', ci);
conn.on('say', function(d) {
$('div').prepend($('<p>').text(d.text));
});
}
$('input').on('keydown', function(e) {
if (e.keyCode == 13) {
conn.publish('say', { text: $(this).val() });
$(this).val('');
}
});
});
</script>
</head>
<body>
<input type="text" placeholder="type and hit enter to send..."/>
<div></div>
</body>
</html>
Regards
Uffe