I am trying to create a websocket connection from JavaScript code to a Java server. I have managed to do this with a unsecure ws connection, but because the website that I want to use this code on is a secure https side, I have to use a secure websocket.
I have spend quite some time on research trying to get this to work, however I can't figure out how to get them connected. I have absolutely no experience with stuff like keystores or ciphers, but I don't need that security, I don't want to send any sensitive data.
Anyways, here is what I've tried:
SLLServerSocket server = (SSLServerSocket) SSLServerSocketFactory
.getDefault().createServerSocket(1234);
SSLSocket client = (SSLSocket) server.accept();
with corresponding JavaScript code:
var socket = new WebSocket("wss://localhost:1234")
socket.onopen = () => console.log("Connected");
socket.onmessage = m => console.log("Message received:", m);
Running this resulted in a Caused by: javax.net.ssl.SSLHandshakeException: No available authentication scheme which I managed to fix by adding
System.setProperty("jdk.tls.server.protocols", "TLSv1.2");
Now I am getting the exception javax.net.ssl.SSLHandshakeException: no cipher suites in common. I've done some research on that as well but whatever I find seems assume that a keystore or something is already there, which it is not for me. In fact I don't really know what encryption it should use, I did not find anything about that
To be fair, part of the problem may very well be that I don't know what to actually search for, but that is why I am asking. There are already articles about these exceptions I am showing, I know them, and they didn't help.
Related
So ive been looking for a way to integrate webRTC into a site im making, but i want to do it on shared hosting. I came across this repo on GitHub by nielsbaloe and it has been a huge help in getting a basic connection.
This is the code i believe is responsible for adding the peer: ( index.html in the repo, line )
function icecandidate(localStream) {
pc = new RTCPeerConnection(configuration);
pc.onicecandidate = function (event) {
if (event.candidate) {
publish('client-candidate', event.candidate);
}
};
try {
pc.addStream(localStream);
}catch(e){
var tracks = localStream.getTracks();
for(var i=0;i<tracks.length;i++){
pc.addTrack(tracks[i], localStream);
}
}
pc.ontrack = function (e) {
document.getElementById('remoteVideo').style.display="block";
document.getElementById('localVideo').style.display="none";
remoteVideo.srcObject = e.streams[0];
};
}
Now the struggle im facing is adding room functionality, and maybe the ability to have more than two concurrent peers present at the same time. I did some experimenting, but in vain. I know that for room functionality id have to tinker around in the php, so at least id like to figure out how to make more than 1 peer possible.
As far as I know, there is no way to re-use the same RTCPeerConnection for multiple peers, so you'll have to do the same thing as 1-on-1 but between every single peer in a group.
As far as signalling, it's pretty simple, goes kind of like this:
Client A -> [Offer] -> Server -> [Offer] -> Client B -> [Answer] -> Server -> [Answer] -> Client A
A nicer explanation at MDN
There isn't necessarily a need for NodeJS or WebSocket. The reason most people go for it it is because the last link in this chain (Server -> Client A) requires server-initiated connection. But that can be substituted with alternative techniques such as (long-)polling. Or, in case of PHP, you might use websocket implementations such as Bloatless or Aerys
To implement the room functionality, you'll have to implement the following:
Variant A (using polling):
An endpoint to throw offers at, e.g. POST /rooms/{id}
An endpoint to regularly check for new offers from, e.g. GET /rooms/{id}
Variant B (with websockets)
Create a broadcast rooms, for example, by dynamically creating HTTP endpoints and websocket server instances. Or by having a single websocket instance but sending whatever room you're intending to join right inside after establishing a connection. From there, it's only a matter of sending correct offers and answers to correct users.
In both cases, you might want to either create multiple offers in advance to pool from the server, or to dynamically create new ones, but, most importantly, make sure you're not connecting the same peers twice, otherwise you will end up with a loop. To prevent it, just provide each user with a randomly generated string to identify themself and send it among offers.
There are turnkey solutions available if you don't want to go this route, but be careful and check whether you can use your own TURN servers with them. A common trend I have noticed is that there are a lot of WebRTC solution providers out there that lure you with their simplicity but then lock you in with their own TURN servers for which you might have to pay a quite hefty bill later on.
I've a client to server Websocket connection which should be there for 40 seconds or so. Ideally it should be forever open.
The client continually sends data to server and vice-versa.
Right now I'm using this sequence:
var socket;
function senddata(data)
{
if (!socket)
{
socket = new WebSocket(url);
socket.onopen = function (evt) {
socket.send(data);
socket.onmessage = function (evt) {
var obj = JSON.parse(evt.data);
port.postMessage(obj);
}
socket.oneerror = function (evt) {
socket.close();
socket = null;
}
socket.onclose = function(evt){
socket = null;
}
}
}
else
{
socket.send(data);
}
}
Clearly as per current logic, in case of error, the current request data may not be sent at all.
To be frank it sometimes gives error that websocket is still in connecting state. This connection breaks often due to networking issues. In short it does not work perfectly well.
I've read a better design : How to wait for a WebSocket's readyState to change but does not cover all cases I need to handle.
Also I've Googled about this but could not get the correct procedure for this.
So what is the right way to send regular data through Websockets which handles well these issues like connection break etc?
An event you don't seem to cover is onclose. Which should work really well, since it's called whenever the connection terminates. This is more reliable than onerror, because not all connection disruptions result in an error.
I personally use Socket.IO, it enables real-time bidirectional event-based communication between client and server.
It is event driven. Events such as
on connection :: socket.on('conection',callback);
and
on disconnect :: socket.on('disconnect',callback);
are built in with socket.io so it can help you with your connection concerns. Pretty much very easy to use, check out their site if you are interested.
I use two-layer scheme on client: abstract-wrapper + websocket-client:
The responsibilities of the websocket-client are interacting with a server, recovering the connection and providing interfaces (event-emitter and some methods) to abstract-wrapper.
The abstract-wrapper is a high-level layer, which interacts with websocket-client, subscribes to its events and aggregating data, when the connection is temporary failed. The abstract-wrapper can provide to application layer any interface such as Promise, EventEmitter and so on.
On application layer, I just work with abstract-wrapper and don't worry about connection or data losing. Undoubtedly, it's a good idea to have here information about the status of connection and data sending confirmation, because it's useful.
If it is necessary, I can provide some code for example
This apparently is a server issue not a problem in the client.
I don't know how the server looks like here. But this was a huge problem for me in the past when I was working on a websocket based project. The connection would continuously break.
So I created a websocket server in java, and that resolved my problem.
websockets depend on lots of settings, like if you're using servlets then servlet container's settings matter, if you're using some php etc, apache and php settings matter, for example if you create a websocket server in php and php has default time-out of 30 seconds, it will break after 30 seconds. If keep-alive is not set, the connection wont stay alive etc.
What you can do as quick solution is
keep sending pings to a server after a certain amount of time (like 2 or 3 seconds, so that if a websocket is disconnected it is known to the client so it could invoke onclose or ondisconnect, I hope you know that there is no way to find if a connection is broken other than failing to send something.
check server's keep-alive header
If you have access to server, then it's timeouts etc.
I think that would help
I have a variable for JSON, but I want to make it where everyone that is on that PHP Page will be able to see the same variable contents.
This code should explain more of my situation.
(I am trying to make it where the page won't reload)
var chats = [];
var j = jQuery.noConflict();
j(document).ready(function()
{
setInterval(function(i){
var txt = "";
var x;
for (x in chats) {
txt += chats[x] + " <br />";
}
document.getElementById("json").innerHTML = JSON.stringify(chats);
}, 1000)
});
j(document).ready(function() {
j('#post_button').click(function() {
$text = $('[name=message]').val();
$sender = $('#texta').val();
chatstuff = {
"sender" : $sender,
"message" : $text,
};
chats.push(chatstuff);
$('[name=message]').val("");
});
});
So when it does document.getElementById("json").innerHTML = JSON.stringify(chats);, I want everyone to be able to see the same chats content when they are on the same page.
JavaScript runs in the user's browser. Any data in a variable is only visible to that client.
In order to synchronize data between clients, you would need to use something like websockets. Each client (user) would send data to your server and the server would relay all client activity to each client.
A very popular JavaScript websockets library is socket.io. You'll find a plethora of "How to create simple chat in JavaScript with websockets" tutorials if you just start searching for them.
Here's a socket.io chat demo that's right on there site.
"Why use websockets instead of Ajax?"
Well, just think about it for a little bit... Ajax is great for clients sending data to the server asynchronously, but what about the server talking to the client?
If user A writes "hello", we can send that to the server using Ajax, but how will users B and C be notified that a new message arrived?
Historically, before websockets, this was done with Ajax "long polling". What that means is each client will make an ajax request to the server every x seconds that asks "Hey, any new messages for me to read?"
If you're implementing a realtime chat app, that means x is going to be something like a max of 5 seconds otherwise users will be too frustrated with the lag.
Pinging our server every 5 seconds to ask the same question over and over is annoying. And it's quite archaic by today's standards. Maybe there's a better way...
"OK, so how does websockets make this better?"
Well websockets allows a connection between the client and server to stay open. This means that the server can send data to the client as soon as data arrives, without the client having to ask for it.
This means that we can ditch the polling and get data sync'd up even faster! Sweet!
"OK, that's great, but I can't rely on bleeding edge technologies..."
Well that's not really a problem either. The reason I recommended a websocket lib (e.g., socket.io) is because the socket.io will make a wide variety of attempts to achieve a socket-like connection in the event that your browser doesn't support actual websockets.
Included in a list of fallback methods is none other than... drumroll, please... Ajax long polling.
"Is there any alternative to socket.io?"
Yep. Now that you know you're looking for it should be easy to find tons of options out there. ws is another great lib that i'd definitely check out if socket.io seems too heavy-handed for you.
no, you have to use a server for this. send new data from this page to the server and the server will update the page for other viewers. consider reading some tutorials like this http://tutorialzine.com/2010/10/ajax-web-chat-css-jquery/
Can anybody give me some sample source code showing how to connect to a SQL Server 2005 database from JavaScript locally? I am learning web programming on my desktop.
Or do I need to use any other scripting language? Suggest some alternatives if you have them, but I am now trying to do it with JavaScript. My SQL Server is locally installed on my desktop — SQL Server Management Studio 2005 and IE7 browser.
You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
document.write(rs.fields(1));
rs.movenext;
}
rs.close;
connection.close;
A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.
And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)
This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.
A perfect working code..
<script>
var objConnection = new ActiveXObject("adodb.connection");
var strConn = "driver={sql server};server=QITBLRQIPL030;database=adventureworks;uid=sa;password=12345";
objConnection.Open(strConn);
var rs = new ActiveXObject("ADODB.Recordset");
var strQuery = "SELECT * FROM Person.Address";
rs.Open(strQuery, objConnection);
rs.MoveFirst();
while (!rs.EOF) {
document.write(rs.fields(0) + " ");
document.write(rs.fields(1) + " ");
document.write(rs.fields(2) + " ");
document.write(rs.fields(3) + " ");
document.write(rs.fields(4) + "<br/>");
rs.movenext();
}
</script>
Web services
SQL 2005+ supports native WebServices that you could almost use although I wouldn't suggest it, because of security risks you may face. Why did I say almost. Well Javascript is not SOAP native, so it would be a bit more complicated to actually make it. You'd have to send and receive SOAP via XmlHttpRequest. Check google for Javascript SOAP clients.
http://msdn.microsoft.com/en-us/library/ms345123.aspx - SQL native WebServices
http://www.google.com/search?q=javascript+soap - Google results for Javascript SOAP clients
Playing with JavaScript in an HTA I had no luck with a driver={SQL Server};... connection string, but a named DSN was OK :
I set up TestDSN and it tested OK, and then var strConn= "DSN=TestDSN"; worked, so I carried on experimenting for my in-house testing and learning purposes.
Our server has several instances running, e.g. server1\dev and server1\Test which made things slightly more tricky as I managed to waste some time forgetting to escape the \ as \\ :)
After some dead-ends with server=server1;instanceName=dev in the connection strings, I eventually got this one to work :
var strConn= "Provider=SQLOLEDB;Data Source=server1\\dev;Trusted_Connection=Yes;Initial Catalog=MyDatabase;"
Using Windows credentials rather than supplying a user/pwd, I found an interesting diversion was discovering the subtleties of Integrated Security = true v Integrated Security = SSPI v Trusted_Connection=Yes - see Difference between Integrated Security = True and Integrated Security = SSPI
Beware that RecordCount will come back as -1 if using the default adOpenForwardOnly type. If you're working with small result sets and/or don't mind the whole lot in memory at once, use rs.Open(strQuery, objConnection, 3); (3=adOpenStatic) and this gives a valid rs.RecordCount
As stated before it shouldn't be done using client side Javascript but there's a framework for implementing what you want more securely.
Nodejs is a framework that allows you to code server connections in javascript so have a look into Nodejs and you'll probably learn a bit more about communicating with databases and grabbing data you need.
I dont think you can connect to SQL server from client side javascripts. You need to pick up some server side language to build web applications which can interact with your database and use javascript only to make your user interface better to interact with.
you can pick up any server side scripting language based on your language preference :
PHP
ASP.Net
Ruby On Rails
(sorry, this was a more generic answer about SQL backends--I hadn't read the answer about SQL Server 2005's WebServices feature. Although, this feature is still run over HTTP rather than more directly via sockets, so essentially they've built a mini web server into the database server, so this answer is still another route you could take.)
You can also connect directly using sockets (google "javascript sockets") and by directly at this point I mean using a Flash file for this purpose, although HTML5 has Web Sockets as part of the spec which I believe let you do the same thing.
Some people cite security issues, but if you designed your database permissions correctly you should theoretically be able to access the database from any front end, including OSQL, and not have a security breach. The security issue, then, would be if you weren't connecting via SSL.
Finally, though, I'm pretty sure this is all theoretical because I don't believe any JavaScript libraries exist for handling the communications protocols for SSL or SQL Server, so unless you're willing to figure these things out yourself it'd be better to go the route of having a web server and server-side scripting language in between the browser and the database.
I'm trying to create a simple nodejs application that connects to the pathofexile.com/trade api.
The problem with this API is that is that you cannot use it unless you're logged in on the main website (my code works in the browser, but I'm trying to make it into a desktop application). There are several other applications that solves this issue by creating a session ID cookie with a users session ID (ID that you can get by logging in to the website). Unfortunately the documentation of the API is very limited and I havn't been able to find any information on how I can create/use the cookie as needed.
If I try to connect to the websocket, without being logged in to the main pathofexile website, I get the following error:
VM58:1 WebSocket connection to 'wss://www.pathofexile.com/api/trade/live/Metamorph/e602K4cL' failed: HTTP Authentication failed; no valid credentials available
I've tried using my sessionID to create a cookie like this by using the built in features in node:
const cookie = { name: 'POESESSID', value: '3acbf42fb842aasdqwe1a0c355f',domain:
'.pathofexile.com' }
session.defaultSession.cookies.set(cookie)
.then(() => {
// success
console.log("Cookie set (?)")
}, (error) => {
console.error(error)
})
Unfortunately, this does not work. I'm very unfamiliar with websockets (only started playing around with any of this a few days ago by accident), and I'm even less familiar with how websockets access and get data from cookies.
I've tried other modules like npm cookie-parser, npm request and npm needle to no avail.
The closest I've gotten to an answer is from a one year old reddit post where the user used C# to get this to work.
This is the code used in that example:
// Setup HTTP connection
HttpClientHandler handler = new HttpClientHandler();
CookieContainer cookieContainer = new CookieContainer();
cookieContainer.Add(composeUrl, new Cookie("POESESSID", sessionId));
handler.CookieContainer = cookieContainer;
HttpClient client = new HttpClient(handler);
If someone could help shine some light on this I'd be very appreciative. I understand that this question is incredibly niche and perhaps I'm asking it in the wrong forum, but I really don't know where to turn.
Appreciate any help!
//Alex