Integrate node js and socket IO with codeigniter - javascript

How can I integrate node.js and socket IO in code igniter.
<script>
// create a new websocket
var socket = io.connect('http://localhost:8000');
// on message received we print all the data inside the #container div
socket.on('notification', function (data) {
var usersList = "<dl>";
$.each(data.users,function(index,user){
usersList += "<dt>" + user.user_name + "</dt>\n" +
"<dd>" + user.user_description + "\n" +
"<figure> <img class='img-polaroid' width='50px' src='" + user.user_img + "' /></figure>"
"</dd>";
});
usersList += "</dl>";
$('#container').html(usersList);
$('time').html('Last Update:' + data.time);
});
</script>
As mentioned in this SO question here. My view file with codeigniter is in localhost/myproject but nodejs listen to port using localhost:8000. So how can I connect socket IO. Like
var socket = io.connect('http://localhost:8000');
//here I need to make socket IO listen to localhost/myproject instead of localhost:8000 .
How is this possible?

I think you're misunderstanding how the socket.io works. You would never listen to your CI view. You would always be sending messages to (and receiving messages from) the NodeJS server on port 8000. Codeigniter's views are simply static, and there is no reason to "listen" to it since it will only load once.
The key point from that answer you referenced:
users will use codeigniter URL and when open the page, i have this script on my CI view page that connects to my Nodejs app
Therefore, you load your browser with the CI view, then listen for events from the NodeJS server through the JavaScript in your CI view.
You can then also push events to the NodeJS server from the JavaScript in your CI view.

Use Dnode, it is an asynchronous RPC system for node.js that makes it talk to php (and vice versa) directly (php side you can call on your codeigniter controller)
I wrote a linkedin post recently about this
https://www.linkedin.com/pulse/make-php-nodejs-talk-each-other-serdar-senay
In the tutorial written for dnode by its founder there's some stale code, so use the code sample in my linkedin post, also dumped below (with better formatting than linkedin):
require ('vendor/autoload.php');
$loop = new React\EventLoop\StreamSelectLoop();
// Connect to DNode server running in port 7070 and call argument with Zing 33
$dnode = new DNode\DNode ($loop);
$dnode-> connect (7070, function ($remote, $connection) {
// Remote is A That Provides Proxy object Methods us all from the Server
$remote-> zing(33, function ($n) Use ($connection) {
echo "n = {$n}\n";
// Once We Have the Result We Can close the connection
$connection->end();
});
});
$loop-> Run();

you can directly link socket.io.js in the codeigniter view.
<script type='text/javascript' src='http://localhost:8000/socket.io/socket.io.js'></script>
then you will be able to make connection to nodejs server from http://localhost/myproject
var socket = io.connect('http://localhost:8000');
However, This way you will do all your client side code in codeigniter view. If you want to use nodejs template engine to send html pages to browser then you can change your node.js server port to 80.

Here's the flow you're going to want to achieve:
1) node.js server setup with socket.io sockets(.on). If you want to have node.js working over socket 80, look into having iptables forward port 80 to port 3000.
2) Add the socket.io client to the code igniter project. You'll be using this to make the initial connection to the node.js/socket.io connection in the CI View.
3) Setup the different events in the View, to trigger the emits to the server as well as what should happen on receiving a socket message. ie: click a button to add an item to the page, it would emit to the server, and then you might have the client receive a message from the server and update the view so that its current.

Related

How to receive data in real time from TCP socket using PHP or JS? [duplicate]

I have a vb.net application that opens a socket and listens on it.
I need to communicate via this socket to that application using a javascript running on a browser. That is i need to send some data on this socket so that the app which is listening on this socket can take that data, do some stuff using some remote calls and get some more data and put it back on the socket that my javascript needs to read and print it in the browser.
Ive tried, socket.io, websockify but none have proved to be useful.
Hence the question, is what i am trying even possible? Is there a way that a javascript running in a browser can connect to a tcp socket and send some data and listen on it for some more data response on the socket and print it to the browser.
If this is possible can some one point me in the right direction as to which would help me establish the goal.
As for your problem, currently you will have to depend on XHR or websockets for this.
Currently no popular browser has implemented any such raw sockets api for javascript that lets you create and access raw sockets, but a draft for the implementation of raw sockets api in JavaScript is under-way. Have a look at these links:
http://www.w3.org/TR/raw-sockets/
https://developer.mozilla.org/en-US/docs/Web/API/TCPSocket
Chrome now has support for raw TCP and UDP sockets in its ‘experimental’ APIs. These features are only available for chrome apps and, although documented, are hidden for the moment. Having said that, some developers are already creating interesting projects using it, such as this IRC client.
To access this API, you’ll need to enable the experimental flag in your extension’s manifest. Using sockets is pretty straightforward, for example:
chrome.experimental.socket.create('tcp', '127.0.0.1', 8080, function(socketInfo) {
chrome.experimental.socket.connect(socketInfo.socketId, function (result) {
chrome.experimental.socket.write(socketInfo.socketId, "Hello, world!");
});
});
This will be possible via the navigator interface as shown below:
navigator.tcpPermission.requestPermission({remoteAddress:"127.0.0.1", remotePort:6789}).then(
() => {
// Permission was granted
// Create a new TCP client socket and connect to remote host
var mySocket = new TCPSocket("127.0.0.1", 6789);
// Send data to server
mySocket.writeable.write("Hello World").then(
() => {
// Data sent sucessfully, wait for response
console.log("Data has been sent to server");
mySocket.readable.getReader().read().then(
({ value, done }) => {
if (!done) {
// Response received, log it:
console.log("Data received from server:" + value);
}
// Close the TCP connection
mySocket.close();
}
);
},
e => console.error("Sending error: ", e)
);
}
);
More details are outlined in the w3.org tcp-udp-sockets documentation.
http://raw-sockets.sysapps.org/#interface-tcpsocket
https://www.w3.org/TR/tcp-udp-sockets/
Another alternative is to use Chrome Sockets
Creating connections
chrome.sockets.tcp.create({}, function(createInfo) {
chrome.sockets.tcp.connect(createInfo.socketId,
IP, PORT, onConnectedCallback);
});
Sending data
chrome.sockets.tcp.send(socketId, arrayBuffer, onSentCallback);
Receiving data
chrome.sockets.tcp.onReceive.addListener(function(info) {
if (info.socketId != socketId)
return;
// info.data is an arrayBuffer.
});
You can use also attempt to use HTML5 Web Sockets (Although this is not direct TCP communication):
var connection = new WebSocket('ws://IPAddress:Port');
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};
http://www.html5rocks.com/en/tutorials/websockets/basics/
Your server must also be listening with a WebSocket server such as pywebsocket, alternatively you can write your own as outlined at Mozilla
ws2s project is aimed at bring socket to browser-side js. It is a websocket server which transform websocket to socket.
ws2s schematic diagram
code sample:
var socket = new WS2S("wss://ws2s.feling.io/").newSocket()
socket.onReady = () => {
socket.connect("feling.io", 80)
socket.send("GET / HTTP/1.1\r\nHost: feling.io\r\nConnection: close\r\n\r\n")
}
socket.onRecv = (data) => {
console.log('onRecv', data)
}
See jsocket. Haven't used it myself. Been more than 3 years since last update (as of 26/6/2014).
* Uses flash :(
From the documentation:
<script type='text/javascript'>
// Host we are connecting to
var host = 'localhost';
// Port we are connecting on
var port = 3000;
var socket = new jSocket();
// When the socket is added the to document
socket.onReady = function(){
socket.connect(host, port);
}
// Connection attempt finished
socket.onConnect = function(success, msg){
if(success){
// Send something to the socket
socket.write('Hello world');
}else{
alert('Connection to the server could not be estabilished: ' + msg);
}
}
socket.onData = function(data){
alert('Received from socket: '+data);
}
// Setup our socket in the div with the id="socket"
socket.setup('mySocket');
</script>
In order to achieve what you want, you would have to write two applications (in either Java or Python, for example):
Bridge app that sits on the client's machine and can deal with both TCP/IP sockets and WebSockets. It will interact with the TCP/IP socket in question.
Server-side app (such as a JSP/Servlet WAR) that can talk WebSockets. It includes at least one HTML page (including server-side processing code if need be) to be accessed by a browser.
It should work like this
The Bridge will open a WS connection to the web app (because a server can't connect to a client).
The Web app will ask the client to identify itself
The bridge client sends some ID information to the server, which stores it in order to identify the bridge.
The browser-viewable page connects to the WS server using JS.
Repeat step 3, but for the JS-based page
The JS-based page sends a command to the server, including to which bridge it must go.
The server forwards the command to the bridge.
The bridge opens a TCP/IP socket and interacts with it (sends a message, gets a response).
The Bridge sends a response to the server through the WS
The WS forwards the response to the browser-viewable page
The JS processes the response and reacts accordingly
Repeat until either client disconnects/unloads
Note 1: The above steps are a vast simplification and do not include information about error handling and keepAlive requests, in the event that either client disconnects prematurely or the server needs to inform clients that it is shutting down/restarting.
Note 2: Depending on your needs, it might be possible to merge these components into one if the TCP/IP socket server in question (to which the bridge talks) is on the same machine as the server app.
The solution you are really looking for is web sockets. However, the chromium project has developed some new technologies that are direct TCP connections TCP chromium

Send data from server through HTML file in nodejs

My goal is to send text left or right triggered from my html file to all clients connected to server (my nodejs server file). I tried many online solutions but i am not able to understand and some of them not working, because am not regular nodejs programmer.
I have created web app in html with two buttons left and right. When i click left button on html file my all connected clients should get text "left". I also created server.js nodejs file which is perfectly communicating with all clients. Problem is how can i get communication between html file and server file.
Note : html file is server side trigger point not client.
server.js
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 8888;
net.createServer(function (sock) {
console.log('connected : ' + sock.remoteAddress + ':'+sock.remotePort);
var ip = sock.remoteAddress.split(':')[3];
console.log(ip);
sock.write('hello client you are connected with server 10.0.0.19...');
sock.on('data', function (data) {
console.log('DATA '+ sock.remoteAddress+' - '+data);
sock.write('you said : '+data);
});
function sendto(result) { //tried call from html file
console.log('sent '+result);
sock.write('data : '+result);
}
sock.on('close', function (data) {
console.log('closed');
});
}).listen(PORT);
console.log('server running on '+PORT);
Help me with way to communicate my html file with server.js, but not as client.
Use SSE , server sent events to send a event from your server to all your connections.
From Client :
Whenever you click the left/button you hit a api of your NODE. The same API when hit will publish a SSE to all the clients.
In the Subscriber End ,
var source = new EventSource("/pageTell"); (an API which your server exposes)
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
HTTP, by default, is a short lived request response connection which is not always connected. Meaning, the server sends out a HTML or related page, and then the connection is disconnected. Based on your use case you need the server to keep the connection open so that all connected clients can be informed of state changes.
For your usecase, you need something like WebSockets (very neatly documented on html5rocks https://www.html5rocks.com/en/tutorials/websockets/basics/). OR if you intend to support older browsers look at socket.io . Socket IO basic sample should be able to help you in achieving your requirements
Use socket.io for this. It has node module as well as client side library.
Implement socket listener on all the clients. Whichever client is listening to the event will receive the data. Emit the data with event name when the button is clicked using the client side javascript of socket io. Check this example out for the same.

how to run node.js client on browser

everyone
I'm very new to node.js.
I'm trying to do a tcp server <-> client using node.js. So far so good.
The server script can be run Ok.
Also the client script can be run OK.
But the problem is I could only get the client to run from the terminal by typing command (node client.js).
The thing is I would like to run it in a browser so I could take the data received from server display on browser.
How do I do that?
Please help.
Kawin.
This is the client code. (I can't remember who originally created this script. I copy and paste it from somewhere but forget to bookmark from which I get the link. Sorry for not putting the credit to the owner of this script.)
var net = require('net');
var HOST = '192.168.0.88';
var PORT = 8888;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('B2\r\n');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
Thank you.
Node.js is not browser javascript. There are many parts of it that use OS features not available in a browser context. The way to do what you're looking to do while staying in the browser for the client, is to not use a TCP socket, but instead look into WebSockets (e.g. socket.io, which offers server and browser clients).
Times are changing. It's just been announced that it might be possible to use node.js in the browser soon. Check out this link: Run Node.js in the browser
The thing is I would like to run it in a browser so I could take the data received from server display on browser.
I think you need 'http' module.
var http=require('http');
var server=http.Server(function(req,res) {
res.end('<p>hello world</p><script>alert("hello world")</script>');
});
server.listen(8080);
so you can get data from browser side by typing URL 'localhost:8080'

instant messaging system using JavaScript

I have a school project where i need to create an instant webbased messageing system.
Ive looked into PHP sockets to complete this task PHP socket manual
From these im starting to see a pattern. As you well know PHP can only run once (from top to bottom) and from these examples i can see that a while loop is what makes the socket listen for new connections. (meaning the php script never stops) these examples the echo the output of the socket.
as far as i can see this is great if you just want a plain site.
However this is not the case. I want to build this application using JavaScript to "ask" the socket if there is any new messages and if there is then render the messages accordingly.
Since im very new to PHP sockets im not sure if this should be done purely by PHP or if it is possible to use JavaScript to listen to the socket (via Ajax) and then print the output as a JSON?
I recommend you to use a third party library (well, an recommend you again this library: cboden/ratchet). Read its tutorials and you will have a cleaner look at how to communicate between browsers ans servers using WebSocket protocol.
The server is absolutely able to be implemented with pure PHP!
In general for push based notifications the protocol you will want (which only works with newer browsers) is WebSockets.
There are a variety of libraries and services which can do this for you:
Pusher, is an online service which can integrate with a variety of languages to give you real time functionality. https://pusher.com/
In JavaScript only, and if you have node you should look at socket.io : http://socket.io/
In .NET land, there is SignalR which is fantastic http://signalr.net/
Not only is it possible to do with PHP but it's also trivial with Thruway. Thruway is a WAMPv2 PHP client/router that uses Ratchet for the Websocket transport. WAMP gives you Sub/Pub and RPC over WebSockets.
You would need to create a simple php router and start it from the command line. Something like this:
<?php
require 'vendor\autoload.php';
use Thruway\Peer\Router;
use Thruway\Transport\RatchetTransportProvider;
$router = new Router();
$transportProvider = new RatchetTransportProvider("127.0.0.1", 9090);
$router->addTransportProvider($transportProvider);
Then on the client, use AutobahnJS or if you're using angular, you can use angular-wamp.
If you still have questions, I'll work up a simple chat example.
I actually used a PHP based websocket and adapted it. I can work both ways if you want. You can store the messages sent to the websocket in an Array or even let them be saved into a database. The client can ask for new messages:
look at this code:
function createConnectionToWebSocket(connection)
{
var host = "ws://[ip of server]:9000/echobot"; // SET THIS TO YOUR SERVER --> 9000 is the port used by websockets.
try {
socket = new WebSocket(host);
console.log('WebSocket - status '+socket.readyState);
socket.onopen = function(msg) {
console.log("Welcome - status "+this.readyState);
};
socket.onmessage = function(msg) {
messageHandlerSocket(msg.data);
};
socket.onclose = function(msg) {
console.log("Disconnected - status "+this.readyState);
if (msg && !msg.wasClean && msg.code == 1006)
{
}
};
socket.onerror = function(msg) {
};
}
catch(ex){
console.log(ex);
}
}
function messageHandlerSocket(msg)
{
//all messages will be send in JSON
var msg = JSON.parse(msg)
//received JSON and check the type. Type is message
switch (msg.type)
{
case "messages" :
//code when the webserver sends back the messages.
break;
}
}
socket.send(JSON.stringify({"type" : "retrievemessages", "user" : user.id}));
Socket.send allows you to send data to the PHP server. I send JSON and parse this on the server. Based on the type argument I let the PHP server send data back to the corresponding user.
I extend this webserver I found on Github.
Run the webserver via a bat-file.
#ECHO OFF
ECHO STARTING WEBSERVER
ECHO USING [dir to php dir]\php\php.exe
#ECHO OFF
START "WEBSOCKET" /wait /B "[dir to php dir]\php\v5.6\php.exe" -f [path to your websocket.php]

Connecting to TCP Socket from browser using javascript

I have a vb.net application that opens a socket and listens on it.
I need to communicate via this socket to that application using a javascript running on a browser. That is i need to send some data on this socket so that the app which is listening on this socket can take that data, do some stuff using some remote calls and get some more data and put it back on the socket that my javascript needs to read and print it in the browser.
Ive tried, socket.io, websockify but none have proved to be useful.
Hence the question, is what i am trying even possible? Is there a way that a javascript running in a browser can connect to a tcp socket and send some data and listen on it for some more data response on the socket and print it to the browser.
If this is possible can some one point me in the right direction as to which would help me establish the goal.
As for your problem, currently you will have to depend on XHR or websockets for this.
Currently no popular browser has implemented any such raw sockets api for javascript that lets you create and access raw sockets, but a draft for the implementation of raw sockets api in JavaScript is under-way. Have a look at these links:
http://www.w3.org/TR/raw-sockets/
https://developer.mozilla.org/en-US/docs/Web/API/TCPSocket
Chrome now has support for raw TCP and UDP sockets in its ‘experimental’ APIs. These features are only available for chrome apps and, although documented, are hidden for the moment. Having said that, some developers are already creating interesting projects using it, such as this IRC client.
To access this API, you’ll need to enable the experimental flag in your extension’s manifest. Using sockets is pretty straightforward, for example:
chrome.experimental.socket.create('tcp', '127.0.0.1', 8080, function(socketInfo) {
chrome.experimental.socket.connect(socketInfo.socketId, function (result) {
chrome.experimental.socket.write(socketInfo.socketId, "Hello, world!");
});
});
This will be possible via the navigator interface as shown below:
navigator.tcpPermission.requestPermission({remoteAddress:"127.0.0.1", remotePort:6789}).then(
() => {
// Permission was granted
// Create a new TCP client socket and connect to remote host
var mySocket = new TCPSocket("127.0.0.1", 6789);
// Send data to server
mySocket.writeable.write("Hello World").then(
() => {
// Data sent sucessfully, wait for response
console.log("Data has been sent to server");
mySocket.readable.getReader().read().then(
({ value, done }) => {
if (!done) {
// Response received, log it:
console.log("Data received from server:" + value);
}
// Close the TCP connection
mySocket.close();
}
);
},
e => console.error("Sending error: ", e)
);
}
);
More details are outlined in the w3.org tcp-udp-sockets documentation.
http://raw-sockets.sysapps.org/#interface-tcpsocket
https://www.w3.org/TR/tcp-udp-sockets/
Another alternative is to use Chrome Sockets
Creating connections
chrome.sockets.tcp.create({}, function(createInfo) {
chrome.sockets.tcp.connect(createInfo.socketId,
IP, PORT, onConnectedCallback);
});
Sending data
chrome.sockets.tcp.send(socketId, arrayBuffer, onSentCallback);
Receiving data
chrome.sockets.tcp.onReceive.addListener(function(info) {
if (info.socketId != socketId)
return;
// info.data is an arrayBuffer.
});
You can use also attempt to use HTML5 Web Sockets (Although this is not direct TCP communication):
var connection = new WebSocket('ws://IPAddress:Port');
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};
http://www.html5rocks.com/en/tutorials/websockets/basics/
Your server must also be listening with a WebSocket server such as pywebsocket, alternatively you can write your own as outlined at Mozilla
ws2s project is aimed at bring socket to browser-side js. It is a websocket server which transform websocket to socket.
ws2s schematic diagram
code sample:
var socket = new WS2S("wss://ws2s.feling.io/").newSocket()
socket.onReady = () => {
socket.connect("feling.io", 80)
socket.send("GET / HTTP/1.1\r\nHost: feling.io\r\nConnection: close\r\n\r\n")
}
socket.onRecv = (data) => {
console.log('onRecv', data)
}
See jsocket. Haven't used it myself. Been more than 3 years since last update (as of 26/6/2014).
* Uses flash :(
From the documentation:
<script type='text/javascript'>
// Host we are connecting to
var host = 'localhost';
// Port we are connecting on
var port = 3000;
var socket = new jSocket();
// When the socket is added the to document
socket.onReady = function(){
socket.connect(host, port);
}
// Connection attempt finished
socket.onConnect = function(success, msg){
if(success){
// Send something to the socket
socket.write('Hello world');
}else{
alert('Connection to the server could not be estabilished: ' + msg);
}
}
socket.onData = function(data){
alert('Received from socket: '+data);
}
// Setup our socket in the div with the id="socket"
socket.setup('mySocket');
</script>
In order to achieve what you want, you would have to write two applications (in either Java or Python, for example):
Bridge app that sits on the client's machine and can deal with both TCP/IP sockets and WebSockets. It will interact with the TCP/IP socket in question.
Server-side app (such as a JSP/Servlet WAR) that can talk WebSockets. It includes at least one HTML page (including server-side processing code if need be) to be accessed by a browser.
It should work like this
The Bridge will open a WS connection to the web app (because a server can't connect to a client).
The Web app will ask the client to identify itself
The bridge client sends some ID information to the server, which stores it in order to identify the bridge.
The browser-viewable page connects to the WS server using JS.
Repeat step 3, but for the JS-based page
The JS-based page sends a command to the server, including to which bridge it must go.
The server forwards the command to the bridge.
The bridge opens a TCP/IP socket and interacts with it (sends a message, gets a response).
The Bridge sends a response to the server through the WS
The WS forwards the response to the browser-viewable page
The JS processes the response and reacts accordingly
Repeat until either client disconnects/unloads
Note 1: The above steps are a vast simplification and do not include information about error handling and keepAlive requests, in the event that either client disconnects prematurely or the server needs to inform clients that it is shutting down/restarting.
Note 2: Depending on your needs, it might be possible to merge these components into one if the TCP/IP socket server in question (to which the bridge talks) is on the same machine as the server app.
The solution you are really looking for is web sockets. However, the chromium project has developed some new technologies that are direct TCP connections TCP chromium

Categories