Allow two clients interact without server - javascript

Is it possible to allow two clients interact directly without a server?
I am referring to websites, for example is it possible to create a chat between two clients that are on the same website using only javascript on the client-side.
If not, what's the minimum server-side to make a chat work between active clients on a website? (eg: one PHP file and no database) ?
My idea:
Storing the conversation would be easily done using localStorage on each client, the problem is how to send some data from client1 to client2 without storing anything (or at most that message) in the database. Also, note that "past" conversations should not visible, so no storage needed for that.
Note that I don't want any nodeJS or websocket solutions, I want something as simple as possible. So, what's the minimum code and files to make a chat between online users?

The WebRTC APIs will allow JavaScript to initiate a direct browser-to-browser connection, but a server is still required to serve the page and coordinate session initiation.
The APIs are still rapidly evolving and only available in bleeding-edge browsers, so it's not yet ready for real production use.
However—to be honest—for what you're trying to do, the easiest option is Node and socket.io:
var http=require('http'), express=require('express'), sio = require('socket.io')
, app=express(), srv = http.createServer(app);
app.use(express.static(__dirname+'/static'));
sio.listen(srv);
srv.listen(80);
...and now you have a working websockets server in 5 lines. Put all your client-side stuff in the static folder and you're good to go.

HTML5 has got a new Web Sockets feature
With this the server intervention is almost nullified..The server and client communicate through the new protocols
ws - Web Sockets protocol
wss - Web Sockets Secure protocol (similar to https)
Live demo

No, It's not possible. If you want a chat box, you have to store the data in the server. And what connects the clients, like display the chat texts and the same things to every client, they come from the server.. So it's not possible like that. Well, even free chat boxes put the data of each sites in their servers.
As for your idea using localStorage, maybe it's possible (But still, using the new WebSocket protocol), but it doesn't work in the time dimension, right? if another user joins, they won't see what has been sent before.

Related

A question about how web applications work and how server-client is implemented

This is kind of a weird question I think to ask, but I have browsing about for the past some time and cannot find a clear definite answer.
I understand that a client connects to its own server and communicates with the web-server through sockets and I kind of see how that works in php (I have never used php but have used sockets before so I understand the concept).
The issue is I'm trying to get a real view of this.
The question is, do websites generally use sockets and contact a web-server to fetch data or the actual html? Or is it a rare choice made in some areas?
If it is generally used, then is the "real" js usually in the server? or is it client-side (for performance sake)?
Context:
Let me explain a bit where I'm coming from, I'm not a web expert, but I am a computer engineering student so most concepts are easy to understand. A "real"-er view of this would be very helpful.
Now, onto why I'm asking this. I'm developing a web-app as part of a project and have done a fair bit of progress on it but everything was done on a local dev server (so basically a client?)
I've started wondering about this because I wanted to use a database for my website and since I want to connect to something, I will need to connect to a web-server first (for security sake).
My question's intent is to guide me on how and most importantly, where, to setup this server.
I don't think showing any code would be of help here, but assume I have my client running on localhost:1234, my database on localhost:3306, I think I should have a web-server on another port so I can establish this communication, but I want to do it in a clean and legitimate way so all of my current solutions can be ported online with little to no changes (except the obvious)
There's a bunch to unpack here.
First of all, servers can be distant or local. Usually they are distant, local server are mostly used for development purposes.
Even if your server is on your local machine, it still isn't the client. The client is the part that is connecting to your server. For web development it is usually the user browser.
Javascript is a language that can be used server-side, with a NodeJS server, but more often client-side, in your user browser.
Your website, or web application, communicate with your server through various means. Most common one is the HTTP protocol, used to make server requests such as data request to populate your page (in case of an API server, REST or otherwise), or simply request the actual page to display in the browser. The HTTP protocol works by resolving URLs, and making requests to your server registered to this url using special methods such as GET, POST, DELETE, etc...
Sockets are used to create a persistent connection with your server that works both ways. It is mostly used for realtime updates, such as a live chat, as it allows you to push updates from the server instead of having the client request everything.
In most cases the database can be found on the same server as the one serving the website or application, as it is a lot easier to handle, and often faster without the extra networks requests to get the data. However it can be placed on another server, with it's own API to get the data (not necessarily web related)
Ports such as 1234 or 3306 are often used for local development, however once your move your project to a host service, this is usually replace by urls. And the host service will provide you with a config to access the associated database. Or if you are building your own server you might still use ports. It is heavily dependent on your server config.
Hope this clear some things up.
In addition to #Morphyish answer, in the simplest case, a web browser (the client) requests an URL from a server. The URL contains the domain name of the server and some parameters. The server responds with HTML code. The browser interprets the code and renders the webpage.
The browser and the server communicates using HTTP protocol. HTTP is stateless and closes the connection after each request.
The server can respond with static HTML, e.g. by serving a static HTML file. Or, by serving dynamic HTML. Serving dynamic HTML requires some kind of server language (e.g. nodejs, PHP, python) that essentially concatenates strings to build the HTML code. Usually, the HTML is created by filling templates with data from the database (e.g. MySQL, Postgres).
There are countless languages, frameworks, libraries that help to achieve this.
In addition to HTML, the server can also serve javascript that is interpreted in the browser and adds dynamics to the webpage. However, there could be 2 types of javascript that should not be mixed. NodeJS runs on the server and formats the server response, client javascript runs on the browser. Remember, client and server are completely isolated and can communicate only through an HTTP connection.
That said, there ways to make persistent connections between client and server with WebSockets, and add all kinds of exotic solutions. The core principle remains the same.
It does not matter if server software (e.g apache, nginx) is running on your local machine or anywhere else. The browser makes a request to an address, the DNS and network stack figures out how to reach the server and makes it work.

Sending files to users with javascript

I searched the web to see if there was a way to send files (photos, videos, messages) to a user using an app. I couldn't find any clear examples or explanations on how to achieve it.
I have no idea, how to do this. Can anyone tell me how this can be done? Any help will be appreciated. I should also probably mention that the ultimate goal of this app is a messaging application.
Not sure what you mean by "sending files" to a user, but if you want them to download a file using javascript, you could use this excellent jQuery plugin: http://jqueryfiledownload.apphb.com/
Of course, there are many alternatives, such as creating an invisible iframe and then loading the url to the file you want your users to download into that iframe. You can read more about this over here: Download File Using Javascript/jQuery
Hope it helps!
First let me tell you that you can use Kandy js sdk, you can find about it here : https://developer.kandy.io/, I didn't test it but it looks very promising and provides many of the features you need.
In case you want to do it on your own(or you're just curious), WebSockets is the main gamer here.
Http protocol as you should know by now is a request-response protocol, the client make a request to the server and the server responds.
But sometimes we want the server to talk to the client in which we can use SSE(Server-Sent events), in other times we want to create a connection between the server and the client and we want both to be able to send to it and receive from it, that's what WebSockets are made for.
In your usecase you could have two strategies : peer-to-peer or centralized, in centralized strategy when user X wants to send something to user Y it has to first send it to the server and the server sends it to user Y.
For this you need websockets, you create a connection between user X and the server and another between the Server and user Y, you send the file from user X to the connection, the server then sends it through the other connection to user Y, user Y can send a new file to the Server so that the Server sends it to user X, and so on so goes.
From this you can conclude that Websockets has server part and client part, normally we launch websockets server that is different than the web server serving the application(both can be on the same Server computer or in different computers), if you don't want to bring your own server you can look at pusher : https://pusher.com/.
Pusher is a cloud service that provide sdks for many languages including javascript, in case you want to have your own server I can't talk about the server-side part of your problem because your question is a javascript question, for the client-part have a look at socket.io, this provides the client part as well as node server part but you can use the client part in case you don't want to use node for the server.
In case you want to build peer-to-peer connections, you can look at simple-peer.

Express web sockets and a central server

I'm creating an app where the server and the clients will run on the same local network. Is it possible to use web sockets, or rather more specifically, socket.io to have one central server and many clients that are running native apps
? The way I understand socket.io to work is that the clients read the web-pages that are served from the server but what happens when your clients become tablet devices running native apps instead of web pages in a browser?
The scenario I'm working with at the minute will have one central server containing a MEAN app and the clients (iPads) will make GET requests to the data available on the server. However, I'd also like there to be real-time functionality so if someone triggers a POST request on their iPad, the server acknowledges it and displays it in the server's client-side. The iPad apps will (ideally) be running native phonegap applications rather than accessing 192.168.1.1:9000 from their browser.
Is this technically possible to connect to the socket server from the native apps or would the devices have to send POST requests to a central server that's constantly listening for new 'messages'? I'm totally new to the whole real-time stuff so I'm just trying to wrap my head around it all.
Apologies if this isn't totally clear, it's a bit hard to describe with just text but I think you get the idea?
Correct me if I am wrong.
You have multiple iPads running native app. They send a POST request to your node JS server which is running in a computer in the same local network. Whenever the server receives a request from app, you want to display that a request has been received in your computer screen.
If my assumptions about the scenario is correct, then it is fairly easy to do. Here are the steps to do it.
Create a small webpage (front end). Load socket IO in the front end page like this -
<script type="text/javascript" src="YOUR_SERVER_IP/socket.io/socket.io.js"></script>
Then connect to server using var socket = io(). This should trigger connection event in your backend.
Handle all POST request from apps normally. Nothing special. Just add a small snippet in between. socket.emit('new_request', request_data). This sends new_request event to front end.
Handle the new_request in your front end using socket.on('new_request', function(request_data) { ... });. That's it. No need to add anything to your native app for realtime update.
The second step would be a little complicated as it is necessary to make socket variable available inside all POST requests. Since you chose node.js, I don't think you need any help with that.
Not totally clear on your project, but I'll try to give you some pointers.
An effective way to send data between native apps and a server is using a REST server. REST is based on HTTP requests and allows you to modify data on the server, which can connect to your database. The data returned is typically either JSON or XML formatted. See here for a brief intro: http://www.infoq.com/articles/rest-introduction
Android/iOS/etc have built in APIs for making HTTP requests. Your native app would send a request to the server, parse the response, and update your native UI accordingly. The same server can be used from a website using jQuery ajax HTTP requests.
Express.js is more suited to serving web pages and includes things like templating. Look into "restify" (see here: mcavage.me/node-restify/) if you just want to have a REST server that handles requests. Both run on top of node.js (nodejs.org).
As far as real-time communication, if you're developing for iOS look into APNS (Apple Push Notification Service). Apple maintains a persistent connection, and by going through their servers you can easily send messages to your app. The equivalent of this on Android is GCM (Google Cloud Messaging).
You can also do sockets directly if that's easier for you. Be careful with maintaining an open socket on a mobile device though, it can be a huge battery drain. Here's a library for connecting ObjC to Socket.IO using websockets, it may be useful for you: https://github.com/pkyeck/socket.IO-objc
Hope that helps!
To answer your question, it is definitely possible. Socket.io would serve as the central server that can essentially emit messages to all of the client. You can also make Socket.io listen for the messages from any of the clients and serve the emitted message to the rest of the clients.
Here's an example of how socket.io can be used. Simply clone, npm install, and run using 'node app.js'
All you have to do is to provide a valid server address when you connect your socket from the iPad clients:
var socket = io.connect( 'http://my.external.nodejs.server' );
Let us know if you need help with actual sending/receiving of socket events.
It is possible to connect to Websockets from your apps.
If you are using PhoneGap then you need a pluging that gives support to websockets in your app (the client) and then use websocket like normal way using Javascript see this.
If your app is native iOS look into this it could help you.
The primary use of the Sockets in your case is to be a bidirectional "pipe" between an app and server. There is no need of server sending the whole web-page to the native app. All what you need is to send some data from server to the client(app) in response to POST (or GET) request and then using this data on client side to update client's UI in real-time. If you are going to use moderate amount of devices (say tens of them), you may have connected all of them to the server permanently keeping individual socket connection open for every individual link server-to-app. Thus you may deliver data and update client's state in real time.
In fact web browsers also employ sockets to communicate to web servers. However as in general case there is no control on amount of concurrent clients in Internet, for the sake of limited networking resources conservation, servers do not keep sockets open for a long time, closing it just after the web-page was sent to client (or timeout has expired). That's how HTTP protocol works on the low level. The server waiting for the HTTP clients (browsers) by listening the 80 port, responding them by sending the whole web page content, then closing the connection and keep waiting for another requests on the same port.
In your case it's basically a good idea to use socket.io as it's a uniform implementation of sockets (ok WebSockets) on both client and server side. The good starting point is here

Is it possible to send data between two browsers on different machines (but on same WLAN) using no servers?

Ultimately what I would like to to is build a Javascript app that runs in the browser, and is able to communicate to other users running the same Javascript app on other machines within the same network. I've been reading up on and playing around with Websockets and webRTC, but they both require a server at some stage of the connection process. I have also looked at PeerJs and OpenPeer, but they too seem to rely on webRTC which in turn requires an intermediate server to setup the connection.
If the users are not connected to the Internet (or to a network running a local server) it doesn't seem possible to use either of the above techniques, right?
Basically what I'm thinking is this:
User A and User B are on two separate machines on the same LAN/WLAN, not connected to the Internet.
User A opens up the app/page in his browser.
User B opens up the app/page in his browser.
User A enters User B's local IP address in a textbox and clicks on "Connect".
User A and User B can now send messages to each other.
Is this possible today? Or is there something being developed that would enable this in the near future?
This is not possible to do directly inside of a browser.
Standard HTTP interaction is based on a request-response model. Web browsers act as the client, sending requests. They are not designed to be able to handle HTTP requests and send responses accordingly, that job belongs to a server.
I know this is an old question, but in case someone finds it relevant:
Today this is possible using WebRTC, a JavaScrip, peer-to-peer, real-time communication protocol.
A library that's available at the time of writing is PeerJS, which supports most browsers, for now except Safari.
PeerJS handles some of the complicated, behind-the-scenes stuff related to NAT and firewalls so that you can send data between two JavaScript clients.

Peer to Peer, Javascript Games

I am writing a simple javascript game for a webpage. I am going to convert it to the desktop using tidesdk. I would like to allow players on different machines to play each other without the need to communicate through a server.
Is this possible in general? Is this Sockets?? Do you have any links of this being done with javascript code?
Is this possible with TideSdk? Do you know of any links to examples of this being done wiht TideSdk?
How do the players know what ip address/port their machine is on so they can give it to the other player?
I am sorry these are vague and open questions, but I don't really know where to start looking for this stuff, as I don't really know what the stuff I am looking for is called.
... Oh, and I don't want to use any third party stuff if I can help it. Maybe the jquery at a push.
This would be impossible with the APIs provided by web browsers (you would need to use something like Socket.IO and communicate through a server, as others have said). Fortunately, since you are using TideSDK, it is possible as long as you don't need a lot of network efficiency. You will need to provide a server, but it will not have to be powerful enough to host the actual games.
The General Client and Server Method
There are other ways to organize a network, but you can look those up if you think they'd be easier to implement.
Your server will host the actual game download and provide matchmaking capabilities. The clients that people download will contact this matchmaking server to find others who want to play.
The matchmaking server should select one of those clients to be a host for the others. Finally, the matchmaking server will tell the client selected as a host that it is the host and give it everyone's connection information (ports and IP addresses) while giving the other clients the connection information for the selected host. The host will connect to the other clients.
The host computer will be the only one that actually does any processing of gameplay, and the other clients just display whatever information the host sends them. The clients render the current state of the game from each player's perspective on their respective computers and capture user input, which is sent to the host for processing.
Implementation
TideSDK provides a Ti.Network.TCPSocket object which can make raw TCP client connections to TCP servers. Unfortunately, it does not also provide a way to make raw TCP servers. Instead, TideSDK provides a Ti.Network.HTTPServer object, which implements the HTTP protocol server over TCP, and a Ti.Network.HTTPClient object, which provides an HTTP client (it is actually just an abstraction over the normal AJAX request API). You can use the provided HTTP server on the host computer and directly connect to it on the clients using the provided HTTP clients. Data will be exchanged using the HTTP protocol. As far as I can tell, this is your only option here.
I did not find any example code out there (beyond what is in the TideSDK documentation) but you might find some if you are really interested.
Next Steps
If I wanted to go ahead with using TideSDK, I would do the following:
Tell the developers of TideSDK that you are interested in a TCP server socket. A raw TCP connection would be much faster than HTTP.
Test out the HTTP connection and find out if it is fast enough for my game.
Yes it's possible in general, and sockets are what you need. Although I don't think it's possible in practice, here's why.
Normally in a P2P game, there would be a server that knows who is online, and what their IP is. When new players connect to the server they will see a list of other users, they can select who they want to play.
Without having the server, there will be no way for users to see who is online, and to answer your 3rd question:
How do the players know what ip address/port their machine is on so they can give it to the other player? It doesn't matter if they can find their own IP, they have no way to find the IP of the opponent (without calling them on the phone :)).
So, if you want to build a game, then you'll need a server. I suggest Node.JS alongside Socket.IO

Categories