I have been trying to implement HTML5 socket server to broadcast whatever it receives to all its connected clients but have no success.
I am new to sockets, can someone pelase suggest me if there is anything already available opensource or what really is it one has to check for doing so. All i could see is client to server communication but there is no way i can send data from one client to server to the other client or simply put, the server just broadcast all messages to all its connected client??
It sounds like you're trying to achieve peer-to-peer communication, which isn't possible over websockets.
It wouldn't be very difficult to set up a fast broadcast server using Node.js and CoffeeScript, that just echoes everything it receives from one socket to all of the others connected:
net = require 'net'
Array::remove = (e) -> #[t..t] = [] if (t = #indexOf(e)) > -1
class Client
constructor: (#socket) ->
clients = []
server = net.createServer (socket) ->
client = new Client(socket)
clients.push client
socket.addListener 'connect', ->
socket.write "Welcome\r\n"
socket.addListener 'data', (data) ->
for c in clients when c isnt client
c.socket.write data
socket.addListener 'end', ->
clients.remove client
socket.end
.listen 4000
console.log "Chat server is running at localhost:4000"
Related
I have a Safari/Firefox/Chrome browser. My browser has devtools.
Is there a way to happy send/edit websocket messages for existing connection?
Or by plugin?
Thank you
You can grab instance of websocket connection and can use it further to send further messages on it.
Grab socket connection instance
You must be aware of websocket connection establishment as below:
websocket = new WebSocket('your-ws-url-goes-here');
Now you can use instance of websocket and can use .send() and .close().
Your question states that you want to use existing connected web socket, you can look for socket connection instance in source code and can use it for sending further messages.
Example to play with
You can play with websocket and its instance here at http://websocket.org/echo.html
Notice here
var wsUri = "wss://echo.websocket.org/";
and function having
websocket = new WebSocket(wsUri);
You so you know websocket is connected and having instance in websocket
You can open devtool and type websocket to see all of the option. So in your case you need to find instance of connection so you can play with it.
About editing existing message
I couldn't find if there is any way to edit sent messages, and i think it should not be there. You can send new message since earlier message must have been responded already.
You can list all WebSocket connections on page in Chrome by opening a console and writing queryObjects(WebSocket). It should list all instances after a while.
Then choose the one you want to use and right-click on it and choose "Store object as global variable".
This will create a new variable like temp1 so you can send messages with temp1.send({websocket: 'message'}).
I have a nodeJS server, that takes JSON from three websites and sends it to be displayed on my website(in JSON). The JSON on the websites that I'm taking from is constantly updated, every 10 seconds. How can I make my NodeJS server constantly update so it has the most up to date data?
I'm assuming this isn't possible without refreshing the page, but it would be optimal if the page wasn't refreshed.
If this is impossible to do with NodeJS and there is a different method of accomplishing this, I would be extremely appreciative if you told me.
Code:
router.get("/", function(req, res){
var request = require('request-promise');
var data1;
var data2;
var data3;
request("website1.json").then(function(body){
data1 = JSON.parse(body);
return request("website2.json");
})
.then(function(body) {
data2 = JSON.parse(body);
return request("website3.json");
})
.then(function(body){
data3 = JSON.parse(body);
res.render("app.ejs", {data1: data1, data2: data2, data3: data3});
})
});
Here's some general guidelines:
Examine the APIs you have available from your external service. Find out if there is anything it offers that lets you make a webSocket connection or some other continuous TCP connection so you can get realtime (or close to realtime) notifications when things change. If so, have your server use that.
If there is no realtime notification API from the external server, then you are just going to have to poll it every xx seconds. To decide how often you should poll it, you need to consider: a) How often you really need new data in your web pages (for example, maybe data that is current within 5 minutes is OK), b) What the terms of service and rate limiting are for the 3rd party service (e.g. how often will they let you poll it) and c) how much your server can afford to poll it (from a server load point of view).
Once you figure out how often you're going to poll the external service, then you build yourself a recurring polling mechanism. The simplest way would be using setInterval() that is set for your polling interval time. I have a raspberry pi node.js server that uses a setInterval() to repeatedly check several temperature sensors. That mechanism works fine as long as you pick an appropriate interval time for your situation.
Then for communication of new information back to a connected web page, the best way to get near "real time" updates form the server is for the web page to make a webSocket or socket.io connection to your server. This is a continuously connected socket over which messages can be sent either way. So, using this mechanism, the client makes a socket.io connection to your server. The server receives that connection and the connection stays open for the lifetime of that web page. Then, anytime your server has new data that needs to be sent to that web page, it can just send a message over that socket.io connection. The web page will receive that message and can then update the contents of the web page accordingly based on the data in the message. No page refresh is needed.
Here's an outline of the server code:
// start up socket.io listener using your existing web server
var io = require('socket.io')(app);
// recurring interval to poll several external web sites.
setInterval(function () {
var results = {};
request("website1.json").then(function (body) {
results.data1 = JSON.parse(body);
return request("website2.json");
}).then(function (body) {
results.data2 = JSON.parse(body);
return request("website3.json");
}).then(function (body) {
results.data3 = JSON.parse(body);
// decide if anything has actually changed on external service data
// and whether anything needs to be sent to connected clients
io.emit("newData", results);
}).catch(function(err) {
// decide what to do if external service causes an error
});
}, 10000);
The client code would then be generally like this:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on("newData", function(data) {
// process new data here and update the web page
});
</script>
I have found a few sparse resources on the matter, but i am looking to build a Perl server as a "microservice". More specifically a web application in LAMPhp/Perl/MariaDB in a SOA format.
What is the best way to go about building an efficient Perl server for our backend? The Web Tier opens a PHP stream TCP socket to a particular Perl server for a particular "service" (high-level service). That server must service many Web servers' requests asynchronously. The service then either connects directly to MySQL to fetch an answer (simple case) or must do some computational work to generate an answer.
My naive implementation is single-tasking:
use IO::Socket::INET;
use Data::Dumper;
use JSON::XS qw(encode_json decode_json);
$| = 1;
my $socket = new IO::Socket::INET (
LocalHost => '0.0.0.0',
LocalPort => '7000',
Proto => 'tcp',
Listen => 5,
Reuse => 1
);
while(1) {
my $client_socket = $socket->accept();
my $client_address = $client_socket->peerhost();
my $client_port = $client_socket->peerport();
my $client_json = "";
$client_socket->recv($client_json, 1024);
my $client_data = decode_json $client_json;
%response = %{process_request($client_data)};
$reply_json = encode_json(\%response);
$client_socket->send($reply_json);
shutdown($client_socket, 1);
}
So, there are obviously problems with this, as it is a a copy-paste example from the documentation. It handles a single socket/request at a time serially.
My question is: "What are best practices in Perl to build a server than can efficiently multiplex and process many incoming requests"?
My own thought on the matter is build a 'select' or 'epoll' main process that forks off to a small pool of worker threads via a Thread::Queue.
Any suggestions?
I would consider using either a complete Framework like Mojolicious, or Dancer, or a Package like Net::Server. Quoting from its perldoc:
"Net::Server" is an extensible, generic Perl server engine.
"Net::Server" attempts to be a generic server as in "Net::Daemon" and "NetServer::Generic". It includes with it the ability to run as an
inetd process ("Net::Server::INET"), a single connection server ("Net::Server" or "Net::Server::Single"), a forking server
("Net::Server::Fork"), a preforking server which maintains a constant number of preforked children ("Net::Server::PreForkSimple"), or as a
managed preforking server which maintains the number of children based on server load ("Net::Server::PreFork"). In all but the inetd type,
the server provides the ability to connect to one or to multiple server ports.
HTH
I'm trying to send some data from flash to a server. I was doing it with a test server and everything was ok. But when I change to test it into a real server it send me an error: " got Alert! Type=22" So I searched about it and I discover that its because the real server runs on HTTPS and the test runs on HTTP. So, reading the documentation of the as3httpclienlib library that I am using, I found that there is a bug with some HTTPS servers and cause some errors and don't leave flash send more than 40kb of data, so that throws the error Type 22 -> Record overflow
This only happens with TLS Sockets so I think that the solution is change the TLSSocket to a SSLSocket.
This is the code that I use to send the data to the server:
var client:HttpClient = new HttpClient();
var uri:URI = new URI("http://www.snee.com/xml/crud/posttest.cgi");
var variables:Array = [{name:"fname", value:"FirstName1"}, {name:"lname", value: "LastName1"}];
client.listener.onData = function(event:HttpDataEvent):void {
// Notified with response content in event.bytes as it streams in
};
client.listener.onComplete = function(event:HttpResponseEvent):void {
// Notified when complete (after status and data)
};
client.postFormData(uri, variables);
How can I change this sockets?
Does anyone have an example?
Is this the solution of the problem?
I'm currently trying to develop a simple Flash game which talks to a node.js server.
My question is this:
How might I go about making a server which differentiates web requests from game requests?
Here are the details of what I've done:
Previously, I used the net and static modules to handle requests from the game client and the browser, respectively.
TwoServers.js
// Web server
var file = new staticModule.Server('./public');
http.createServer(function(req, res){
req.addListener('end', function(){
file.serve(req, res, function(err, result){
// do something
});
});
}).listen(port1, "127.0.0.1");
// Game Server
var server = net.createServer(function(socket)
{
// handle messages to/from Flash client
socket.setEncoding('utf8');
socket.write('foo');
socket.on('data', onMessageReceived);
});
server.listen(port2, "127.0.0.1");
I'd like to do the above with just an Express server listening in on a single port, but I'm not sure how to go about doing that.
Here's what I'm thinking it might look like (doesn't actually work):
OneServer.js
var app = express();
app.configure(function()
{
// ...
app.use('/',express.static(path.join(__dirname, 'public'))); // The static server
});
app.get('/', function(req, res) // This is incorrect (expects http requests)
{
// Handle messages to/from Flash client
var socket = req.connection;
socket.setEncoding('utf8');
socket.write('foo');
socket.on('data', onMessageReceived);
});
app.listen(app.get('port')); // Listen in on a single port
But I'd like to be able to differentiate from web page requests and requests from the game.
Note: Actionscript's XMLSocket makes TCP requests, so using app.get('/') is incorrect for two reasons:
When Flash writes to the socket, it isn't using the http protocol, so app.get('/') will not be fired when the game tries to connect.
Since I don't have access to correct the net.Socket object, I cannot expect to be reading or writing from/to the correct socket. Instead, I'll be reading/writing from/to the socket associated with the web page requests.
Any help on this would be much appreciated (especially if I'm reasoning about this the wrong way).
When a TCP connection is opened to a given port, the server (Node + Express) has no way of telling who made that connection (whether it's a browser or your custom client).
Therefore, your custom client must speak HTTP if it wishes to communicate with the Express server sitting on port 80. Otherwise, the data you send over a freshly opened socket (in your custom protocol) will just look like garbage to Express, and it will close the connection.
However, this doesn't mean you can't get a TCP stream to speak a custom protocol over – you just have to speak HTTP first and ask to switch protocols. HTTP provides a mechanism exactly to accomplish this (the Upgrade header), and in fact it is how WebSockets are implemented.
When your Flash client first opens a TCP connection to your server, it should send: (note line breaks MUST be sent as CRLF characters, aka \r\n)
GET /gamesocket HTTP/1.1
Upgrade: x-my-custom-protocol/1.0
Host: example.com
Cache-Control: no-cache
The value of Upgrade is your choice, Host MUST be sent for all HTTP requests, and the Cache-Control header ensures no intermediate proxies service this request. Notice the blank line, which indicates the request is complete.
The server responds:
HTTP/1.1 101 Switching Protocols
Upgrade: x-my-custom-protocol/1.0
Connection: Upgrade
Again, a blank line indicates the headers are complete, and after that final CRLF, you are now free to send any data you like in any format over the TCP connection.
To implement the server side of this:
app.get('/gamesocket', function(req, res) {
if (req.get('Upgrade') == 'x-my-custom-protocol/1.0') {
res.writeHead(101, { Upgrade: req.get('Upgrade'), Connection: 'Upgrade' });
// `req.connection` is the raw net.Socket object
req.connection.removeAllListeners(); // make sure Express doesn't listen to the data anymore... we've got it from here!
// now you can do whatever with the socket
req.connection.setEncoding('utf8');
req.connection.write('foo');
req.connection.on('data', onMessageReceived);
} else res.send(400); // bad request
});
Of course, remember that TCP is not a message-based protocol, it only provides a stream, and thus the data events of a Socket can either fragment a single logical message into multiple events or even include several logical messages in a single event. Be prepared to manually buffer data.
Your other option here is to use socket.io, which implements a WebSockets server plus its own protocol on top of the WebSockets protocol. The WebSockets protocol is message-based. It mostly works just like I've outlined here, and then after HTTP negotiation adds a message framing layer on top of the TCP connection so that the application doesn't have to worry about the data stream. (Using WebSockets also opens the possibility of connecting to your server from a HTML page if necessary.)
There is a Flash socket.io client available.