Client side tcp with node.js/socket.io? - html

I'm new to node.js/socket.io so I don't really know what I'm doing, but I've got this for my server side:
var app = require('net')
, fs = require('fs')
var server = app.createServer(function (socket) {
socket.write("Echo server\r\n");
socket.pipe(socket);
socket.on('data', function(data) {
console.log(data);
});
});
var io = require('socket.io').listen(server)
server.listen(81);
So the tcp server works when I use nc localhost 81 and send it data. However, I don't know how to connect and send data to the tcp server on a website from the server side using script tags. So what would the client side be to connect to this tcp server and send data to it?
Thanks!
Newly added code:
Server:
var app = require('net')
, fs = require('fs')
var sockets_list = [];
var server = app.createServer(function (socket) {
sockets_list.push(socket);
socket.write("Echo server\r\n");
socket.on('data', function(data) {
console.log(data);
for (var i = 0; i < sockets_list.length; i++) {
sockets_list[i].write(data);
}
});
socket.on('end', function() {
var i = sockets_list.indexOf(socket);
sockets_list.splice(i, 1);
});
});
server.listen(81);
Client:
<script type="text/javascript" src="http://localhost:82/socket.io/socket.io.js"> </script>
<script>
var socket = io.connect('http://localhost:81');
socket.on('connect', function () {
socket.send('hi');
});
socket.send('hi1');
socket.emit('hi2');
alert('here');
</script>
What happened:
I have a webpage loading which takes one socket and a nc localhost 81 which takes up another socket. So the nc displays everything the web page sends. After I connect the webpage, the alert('here'); is executed and the nc shows the http request, however, nothing else is sent to the tcp server, and the webpage is in constant refresh status. Why does the webpage never fully load, the 'hi' messages never get sent, and what about the http request to a tcp server? Why doesn't my tcp client fail with my tcp server?

Socket.io's how to use page shows you exactly how to do that.
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost/');
socket.on('connect', function () {
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
</script>

Related

How to display connected clients using node.js and socket.oi.js on HTML

I am new with node.js and socket.io i was able to start a local server via node.js and get the numbers of client connected on port 3000 using console.log now my next step is displaying it on my HTML, i was reading about how to include socket.io.js on HTML and tried the on('connect') method but its returning a undefined error , Any advice would be great thanks in advance!
My server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.PORT || 3000);
console.log('listening to port 3000, server is running..');
app.get('/', function (req,res){
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection',function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
//Disconnect
socket.on('disconnect', function(data){
users.splice(users.indexOf(socket.username), 1);
updateUsernames();
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: %s sockets connected', connections.length);
});
});
On my index.html
//This is located on my html head tag
<script src="http://localhost/socket.io/socket.io.js"></script>
<div class="col-lg-12">
<h1 id="users"></h1>
</div>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('connect',function(){
$('#users').html = socket.users.length;
));
</script>
I manage to display the numbers of connected users on client side by emitting a event than client will receive and display it.
revised my server.js
io.sockets.on('connection',function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
//added this below
io.sockets.emit ('totalUsers', {count: connections.length});
//Disconnect
socket.on('disconnect', function(data){
users.splice(users.indexOf(socket.username), 1);
updateUsernames();
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: %s sockets connected', connections.length);
//added this below
io.sockets.emit ('totalUsers', {count: connections.length});
});
Then on my index.html
socket.on('totalUsers', function(data){
console.log(data.count);
$users.html('Total connected users: '+data.count);
});
You must include or link your socket.io.js before the io.connect() on your html. like this
<script type="text/javascript" src="assets/nodejs/node_modules/socket.io-client/dist/socket.io.js"></script>
you can use this cdn
https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js
but it is better to use your socket.io.json your local folder it is in the node_modules/socket.io-client/dist/socket.io.js if you are using latest version of node.
Hope it will help.

When opening multiple clients, old client does not get updated using nodejs web socket

My goal is when I open a new browser(client), the message sent from the server in the previous client gets updated as well.
Currently,
The clients send messages to the server, the server stores them in localStorage as an array and should send it back to all the clients. All clients should get the same array of messages. It works like ajax call.
As of right now, when I open the first browser, the message is sent to the server and received in the client successfully, and then I open the second one(it works) but the message is not updated in the first browser. PS this acts like a forum, when somebody posts a messages to server, all users should be able to see it.
Here's my code for server:
<html>
<head>
<!-- This is the websocket SERVER -->
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
</head>
<body>
<div id="msg"></div>
<script>
// connect to WEBSOCKET server
var socket = io.connect('http://localhost:5000',{'forceNew':true} );
// Fire an event (that the server will handle
socket.emit('myEvent', 'Hello Message from the client');
// Attach event handler for event fired by server
socket.on('server', function(data) {
var elem = document.getElementById('msg');
console.log(data);
elem.innerHTML += "<br>" + data; // append data that we got back
});
</script>
</body>
</html>
Here's for client:
//---------------------------------------------------------------
// The purpose is to introduce you to websockets
// This is a SERVER that is SEPARATE from the http server.
//
// Your webpage (in this case the index.html in this directory)
// will be SERVED by the http server. THEN, it will connect to the
// websocket server. Then - they will talk to each other!
//
// Note that in regular http - the server cannot initiate a conversation
// Here, the websocket server sends a message to the client browser.
//
// This example has THREE parts
// 1) The http server code (which is same as what we did earlier)
// 2) This code - this is the web socket server
// It prints what it got from client. It also sends a message to the
// client after every 1 second.
// 3) The html or client code. Note how it connects to the websocket
// and how it sends and receives messages
//
// To RUN THIS EXAMPLE
// First, run node httpServer.js on one terminal
// Next, run node 1_ws.js on another terminal
// Next, type localhost:4000/index.html on some browser
//
//---------------------------------------------------------------
var items=[];
var io = require('socket.io').listen(5000);
if (typeof localStorage === "undefined" || localStorage === null) {
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
}
io.sockets.on('connection', function(socket) {
socket.on('myEvent', function(content) {
//i need to store the content
items.push(content);
localStorage.setItem("list",JSON.stringify(items));
socket.emit('server', JSON.parse(localStorage.getItem("list")));
});
});
I'm running on the local server:( you can ignore the local server if you want, the above code can function on their own)
//---------------------------------------------------------------
// The purpose is to serve a file!
//---------------------------------------------------------------
var util = require('util');
var path = require('path');
var http = require('http');
var fs = require('fs');
var server = http.createServer();
// attach handler
server.on('request', function (req,res) {
var file = path.normalize('.' + req.url);
fs.exists(file, function(exists) {
if (exists) {
var rs = fs.createReadStream(file);
rs.on('error', function() {
res.writeHead(500); // error status
res.end('Internal Server Error');
});
res.writeHead(200); // ok status
// PIPE the read stream with the RESPONSE stream
rs.pipe(res);
}
else {
res.writeHead(404); // error status
res.end('NOT FOUND');
}
});
}); // end server on handler
server.listen(4000);
console.log("start");
You are sending response to only client who sent message to sever only,
To send to all clients which are connected you must use this,
io.emit('server', JSON.parse(localStorage.getItem("list")));
Visit this answer for all
Responses

Socket.io not responding, Node.js

I'm moving my code to a server. This code works and renders database information perfectly on my own server I set up on localhost, however an error from index.html stating "io is not defined" displays when I run the code from my server. For whatever reason socket.io is not being recognized. Also, nothing is shown if I type in localhost:3000 in my browser. Any help would be greatly appreciated.
I have two files, server.js and index.html.
server.js:
var mysql = require('mysql')
var io = require('socket.io').listen(3000)
var db = mysql.createConnection({
host: '127.0.0.1', // Important to connect to localhost after connecting via ssh in screen
user: 'username',
password: '12345',
database: '12345',
port: 3306
})
// Log any errors connected to the db
db.connect(function(err){
if (err) console.log(err)
})
// Define/initialize our global vars
var notes = []
var isInitNotes = false
var socketCount = 0
//Socket.io code below
io.sockets.on('connection', function(socket){
// Socket has connected, increase socket count
socketCount++
// Let all sockets know how many are connected
io.sockets.emit('users connected', socketCount)
socket.on('disconnect', function() {
// Decrease the socket count on a disconnect, emit
socketCount--
io.sockets.emit('users connected', socketCount)
})
socket.on('new note', function(data){
// New note added, push to all sockets and insert into db
notes.push(data)
io.sockets.emit('new note', data)
// Use node's db injection format to filter incoming data
db.query('INSERT INTO notes (note) VALUES (?)', data.note)
})
console.log("10");
// Check to see if initial query/notes are set
if (! isInitNotes) {
// Initial app start, run db query
db.query('SELECT * FROM `Users`')
.on('result', function(data){
// Push results onto the notes array
//console.log(notes);
notes.push(data)
})
.on('end', function(){
// Only emit notes after query has been completed
socket.emit('initial notes', notes)
})
isInitNotes = true
} else {
// Initial notes already exist, send out
socket.emit('initial notes', notes)
}
})
index.html: (thinking the problem is in either the way I'm linking my socket.io.js file, or in the line of code where I declare the variable "socket")
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- Script below works with my server I set up on local host
<script src="http://localhost:3000/socket.io/socket.io.js"></script>-->
<!-- script below properly links to the socket.io.js file in my directory, and throws no errors-->
<script type= "node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>
<script>
$(document).ready(function(){
var socket = io.connect('http://localhost:3000'); //LINE OF CODE IN QUESTION
//Code below not really relevant to problem, but still part of my project.
socket.on('initial notes', function(data){
var html = ''
for (var i = 0; i < data.length; i++){
// We store html as a var then add to DOM after for efficiency
html += '<li>' + data[i].Name + '</li>'
}
$('#notes').html(html)
})
// New note emitted, add it to our list of current notes
socket.on('new note', function(data){
$('#notes').append('<li>' + data.Name + '</li>')
})
// New socket connected, display new count on page
socket.on('users connected', function(data){
$('#usersConnected').html('Users connected: ' + data)
})
// Add a new (random) note, emit to server to let others know
$('#newNote').click(function(){
var newNote = 'This is a random ' + (Math.floor(Math.random() * 100) + 1) + ' note'
socket.emit('new note', {note: newNote})
})
})
</script>
<ul id="notes"></ul>
<div id="usersConnected"></div>
<div id="newNote">Create a new note:</div
SOLVED!
Figured it out. I used "script src="my servers ip address:3000/socket.io/socket.io.js" and then change the variable socket to var socket = io.connect('Servers ip address:3000'); So the answer was to take out localhost all together.
I believe there could be a problem loading Socket.io from your server if it works locally (perhaps a permissions issue?), try loading it from Socket.io CDN to test.
<script src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>

Displaying streaming twitter on webpage with socket.io/node.js

I'm trying to build a Twitter streaming web application using node.js socket.io and twit.
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
,Twit = require('twit')
, io = require('socket.io').listen(server);
server.listen(8080);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var watchList = ['love', 'hate'];
io.sockets.on('connection', function (socket) {
console.log('Connected');
var T = new Twit({
consumer_key: ''
, consumer_secret: ''
, access_token: ''
, access_token_secret: ''
})
T.stream('statuses/filter', { track: watchList },function (stream) {
stream.on('tweet', function (tweet) {
io.sockets.emit('stream',tweet.text);
console.log(tweet.text);
});
});
});
Here's my client side
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
$(function(){
var socket = io.connect('http://localhost:8080');
socket.on('tweet', function(tweet) {
$(
'<div class="tweet">' + tweet.text + '</div>');
});
});
</script>
</div>
When I run node app.js and try to connect to localhost:8080 I just get a blank page, even if everything ( soket.io, jquery, ... ) seems to have loaded correctly.
Here's a sample of the server output :
info - socket.io started
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized pwH0dbx4WvBhzSQXihpu
debug - setting request GET /socket.io/1/websocket/pwH0dbx4WvBhzSQXihpu
debug - set heartbeat interval for client pwH0dbx4WvBhzSQXihpu
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"stream","args":["RT #mintycreative: Great to chat today RT #SharonHolistic: Treatments available tomorrow http://t.co/5Poq3KU08u Book yours now #WestMidsHou…"]}
debug - websocket writing 5:::{"name":"stream","args":["RT #laurenpeikoff: #BREAKING #ScottsdalePD confirms - police are investigating Michael Beasley for alleged sexual assault. #12News #azcentr…"]}
Hope you can help me to correct my mistakes.
Problem solved
Here's the code without any mistakes : (server side)
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
,Twit = require('twit')
, io = require('socket.io').listen(server);
server.listen(8080);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var watchList = ['love', 'hate'];
var T = new Twit({
consumer_key: ''
, consumer_secret: ''
, access_token: ''
, access_token_secret: ''
})
io.sockets.on('connection', function (socket) {
console.log('Connected');
var stream = T.stream('statuses/filter', { track: watchList })
stream.on('tweet', function (tweet) {
io.sockets.emit('stream',tweet.text);
});
});
});
(client-side)
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('stream', function(tweet){
$('#tweetd').append(tweet+'<br>');
});
</script>
<div id="tweetd"></div>
</div>
The first issue is that you are constructing a new twitter listener each time a socket connection is opened. You should move that outside of the connection event. This is likely not ideal. I'm not sure how the twitter module is handling that internally but it likely actually is creating a new connection to their API each time a websocket connects.
On the client side you jQuery could bit a bit different. If you just wanted to add a tweet to the page each time a tweet occurs, append a new tweet to the body element with $('body').append()
See this gist for reference.

Socket.IO Websocket Send message not working with Firefox and Chrome

I have a running server with apache and Socket.IO. I'm trying to send and receive message using socket.io on my website.
This is the code of my server:
var fs = require('fs');
var hskey = fs.readFileSync('file.key');
var hscert = fs.readFileSync('file.crt');
var options = {
key: hskey,
cert: hscert
};
var app = require('https').createServer(options);
var io = require('/usr/local/lib/node_modules/socket.io').listen(app);
app.listen(8181);
io.sockets.on('connection', function (socket) {
socket.emit('serverMessage', 'Bienvenue master!');
socket.broadcast.emit('serverMessage', 'New user online');
});
And this is the webpage:
<!doctype html>
<html>
<head>
<title>Socket.io Test</title>
<script src="./socket.io.js"></script>
</head>
<body>
<script>
var socket;
var firstconnect = true;
function connect() {
if(firstconnect) {
socket = io.connect('https://secure.mysite.com:8181');
socket.on('serverMessage', function(data){ message(data); });
socket.on('connect', function(){ status_update("Connected to Server"); });
socket.on('disconnect', function(){ status_update("Disconnected from Server"); });
socket.on('reconnect', function(){ status_update("Reconnected to Server"); });
socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in "
+ nextRetry + " seconds"); });
socket.on('reconnect_failed', function(){ message("Reconnect Failed"); });
firstconnect = false;
}
else {
socket.socket.reconnect();
}
}
function disconnect() {
socket.disconnect();
}
function message(data) {
document.getElementById('message').innerHTML += "<br>" + "Server says: " + data;
}
function status_update(txt){
document.getElementById('status').innerHTML = txt;
}
function esc(msg){
return msg.replace(/</g, '<').replace(/>/g, '>');
}
function send() {
socket.send('clientMessage', 'world');
};
</script>
<h1>Socket.io Test</h1>
<div><p id="status">Waiting for input</p></div>
<div><p id="message"></p></div>
<button id="connect" onClick='connect()'/>Connect</button>
<button id="disconnect" onClick='disconnect()'>Disconnect</button>
<button id="send" onClick='send()'/>Send Message</button>
</body>
</html>
Everything seems to work fine under Safari (websocket) and Opera (json pooling) but with Firefox and Chrome (websocket) I cannot send any message from the client to the server. Everything else is working, I can handshake, connect and gets server messages. I made allot of research but seems like I'm the only one with this problem.
Thanks for helping me!
I found the problem, I was using a different version of socket.io.js then the server side.
when you attach the socket.io module to express it intercepts the socket.io route.
So when you request "https://secure.mysite.com:8181/socket.io" it will respond with
"Welcome to socket.io."
So when you request the client side socket.io.js it comes directly from the socket.io module.
"https://secure.mysite.com:8181/socket.io/socket.io.js"
So If you wan't to mod the client side library you could create a modified copy and let express serve up the file, but as you update socketio through npm you'll have to bump up your modified copy as well manually.
if in FireFox you get this error - first check enabled or no proxy. and turnoff proxy if enabled.