Problem with first program in socket.io - node.js

I am having some problems in executing my first socket.io program. Here is the code
var io=require('socket.io');
var http=require('http');
server =http.createServer(function(req,res) {
res.writeHead(200,{'Content-Type':'text/html'});
res.write('welcome');
res.end();
});
server.listen(7777);
var socket = io.listen(server);
socket.on('connection', function (client) {
console.log('client connected');
client.emit('news', { hello: 'world' });
client.on('another', function (data) {
console.log(data);
});
});
And here is my client side code
<html>
<head>
<script type="text/javascript" src="http://localhost:7777/socket.io/lib/socket.io.js"> </script>
<script type="text/javascript">
var socket = io.connect("http://localhost:7777");
socket.on('news',function(data) {
alert(data);
socket.emit('another',{my:'data'});
});
</script>
</head>
</html>
EDIT: Now, i get an error in my server terminal "info - client protocol unsupported"
what am i doing wrong here? Thanks

You are trying to import a javascript file from the socket io port instead of the web server port.
<script type="text/javascript" src="http://localhost:7777/socket.io/lib/socket.io.js"> </script>
You need to give the correct src parameter. For newer version of socket io, this would be something like socket/socket.io.js.

Related

socket io NOT FOUND ERROR?

I'm trying to learn socket.io and Nodejs for the first time.
I have installed the nodejs and socket.io on my server in the root. everything is installed in the root.
on my domain, i created a test-folder and created an index.html file in that folder and placed this code inside it:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.2/socket.io.min.js"></script>
<script>
$(function(){
var iosocket = io.connect();
iosocket.on('connect', function () {
$('#incomingChatMessages').append($('<li>Connected</li>'));
iosocket.on('message', function(message) {
$('#incomingChatMessages').append($('<li></li>').text(message));
});
iosocket.on('disconnect', function() {
$('#incomingChatMessages').append('<li>Disconnected</li>');
});
});
$('#outgoingChatMessage').keypress(function(event) {
if(event.which == 13) {
event.preventDefault();
iosocket.send($('#outgoingChatMessage').val());
$('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val()));
$('#outgoingChatMessage').val('');
}
});
});
</script>
</head>
<body>
Incoming Chat: <ul id="incomingChatMessages"></ul>
<br />
<input type="text" id="outgoingChatMessage">
</body>
</html>
I then went back to the root and created an app.js file and placed this code in it:
var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/var/www/vhosts/my-website.net/httpdocs/test-folder/index.html'));
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
socketio.listen(server).on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
And ran this command from the SSH:
node app.js
The command above retunr this:
Listening at: http://localhost:8080
I then opened the index.html file from the browser like so:
http://my-website.net/test-folder/index.html
but when i looked inside the console, i see the following error repeating over and over:
socket.io.min.js:1 GET http://my-website.net/socket.io/?EIO=3&transport=polling&t=1505580173244-3 404 (Not Found)
I have no idea what that means or what i need to do. could someone please advise on this issue?
any help would be appreciated.
Thanks in advance.
your first problem is inside your head tag.If you've installed socket.io there is no need to take it by link
let's replce this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.2/socket.io.min.js"></script>
with this one:
<script src="/socket.io/socket.io.js"></script>

socket connection closed before receiving a handshake response

I have written code for socket from :source
My code looks like this.
var port = 8081;
var app = require('http').createServer();
var io = require('socket.io')(app);
app.listen(port);
io.on('connection', function (socket) {
console.log("New user connected.");
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
console.log("server listening on: " + port);
But when I am testing it on here (ws://localhost:8081). I am getting
ERROR: undefined
DISCONNECTED
In console I am getting error:
WebSocket connection to 'ws://localhost:8081/?encoding=text' failed: Connection closed before receiving a handshake response
You need to use the socket.io client library, either getting it, from here, or referencing their CDN from your page like this:
<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
Additionally, whenever you start a socket.io server, socket.io will be served from http://<your-server-address>/socket.io/socket.io.js. You should be able to test your server using this simple page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://localhost:8081/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:8081/');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</head>
<body>
</body>
</html>
You can read more about why you can't connect from the websocket.org site on this github issue.

I can't connect to server(AWS Amazon EC2) using Socket.io with Phonegap on iOS device

I uploaded a server-side code to AWS Amazon EC2 with node.js and socket.io.
When I connect to that server from browser(both on desktop and ios safari), it works with no problem.
But, when I create a cordova project and modify some of the codes to comply with cordova, get it run on ios device, it doesn't work!
I tried
<access origin="My-server-side-url-comes-here*"/>
but it didn't solve the problem.
Also, i opened up port :9000 on EC2 for TCP connection.
It seems that socket = io.connect(serverUrl); is causing problem..
I've been struggling to get this work for days now...
Can anyone tell me how to get socket.io work with external host, phonegap, and ios?
server side code uploaded to AWS Amazon EC2 (app.js)
var http = require('http');
var socketio = require('socket.io');
var server = http.createServer(function (request, response){
console.log('server created');
}).listen(9000, function(){
console.log('server running!');
});
var io = socketio.listen(server);
io.sockets.on('connection', function(socket){
socket.on('msg', function(data){
console.log(data);
io.sockets.emit('msg_by_server', "server got your msg:"+data);
});
});
client-side code that works with desktop browsers and iPhone safari(which works fine) (index.html)
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script>
var socket;
var serverUrl = "sampleURL.compute.amazonaws.com:9000";
window.onload = function(){
socket = io.connect(serverUrl);
socket.on('msg_by_server', function(data){
alert(data);
});
}
var sendMessage = function(){
socket.emit('msg', 'msg from client');
}
</script>
</head>
<body>
<button onclick = 'sendMessage();'>Message Send</button>
</body>
</html>
different client-side code used for phonegap(which doesn't work) (index.html)
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
alert('check1');
var socket="";
app.initialize();
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert('check2'); // shows up
var serverUrl = "sameURL.compute.amazonaws.com:9000";
socket =io.connect(serverUrl);
alert('check3'); // doesn't show up
socket.on('connect', function(){
socket.on('msg_by_server', function(data){
alert(data);
});
socket.emit('msg', 'msg from client')
});
}
var sendMessage = function(){
alert(socket);
socket.emit('msg', 'msg from client');
};
</script>
</head>
<body onload="onDeviceReady();">
<!--
i put onload="onDeviceReady();" because
document.addEventListener("deviceready", onDeviceReady, false);
doesn't seem to work for some reason..
-->
<button onclick = 'sendMessage();'>amessageSend</button>
</body>
</html>

NodeJS and socket.io can't send message

today I follow an tutorial by Gonzalo Ayuso at http://gonzalo123.com/2011/05/23/real-time-notifications-part-ii-now-with-node-js-and-socket-io/ but it can't send the message
Here is my server.js
var http = require('http');
var io = require('socket.io');
server = http.createServer(function(req, res){
});
server.listen(8000);
//socket.io
var socket = io.listen(server);
socket.set('transports', ['websocket']);
console.log("Start");
socket.on('connection', function(client){
client.on('message', function(msg){
console.log(msg);
socket.broadcast(msg);
})
});
and the client.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Comet Test</title>
</head>
<body>
<p><a id='customAlert' href="#" onclick='socket.send("customAlert")'>publish customAlert</a></p>
<p><a id='customAlert2' href="#" onclick='socket.send("customAlert2")'>publish customAlert2</a></p>
<script src="http://localhost:8000/socket.io/socket.io.js" type="text/javascript"></script>
<script type="text/javascript">
// Start the socket
var socket = io.connect('http://localhost:8000');
socket.on('message', function(msg){
console.log(msg);
});
</script>
</body>
</html>
I have edited it just a little bit to run on my server. But the client doesn't send message to server. Can anybody help me? Sorry for my bad English.
I have found out that the client can't connect to server but I don't know why?
My computer is running xampp with apache server. Maybe it's problem?
Updated:
I have just set transports to xhr-polling and it connect success. Why doesn't it accept websocket?
you need to read more carefully the tutorials about socket.io
first of all to call some event, you need to emit the event name:
socket.emit('my other event', { my: 'data' });
thats mean, on your onclick in anchor need to call socket.emit ..., or to call some function like:
function call_my_event(name){
socket.emit(name,{my : 'data'});
}
I have found out my problem. It's about firewall or proxy or something else in my computer block websocket protocol. I tested that code on another computer and it works fine. So I have to re-install my system and websocket is available for me :D

Simple nodeJS example not working with socket.io

Have been struggling all day trying to make this simple example work using socket.io. I've tried initially on Windows 7 with Cygwin. Have since also tried on OS X, with the same result.
When running the script, it shows this...
2 May 20:57:47 - socket.io ready - accepting connections
But visiting the index.html page doesnt show a client has even connected.
index.html
<html>
<head>
<script type="text/javascript" src="socket.io.js"></script>
<script type="text/javascript">
var socket = new io.Socket('localhost',{'port':8090});
socket.connect();
socket.on('connect', function(){
console.log('connected');
socket.send('hi!');
});
socket.on('message', function(data){
console.log('message recived: ' + data);
});
socket.on('disconnect', function(){
console.log('disconected');
});
</script>
</head>
<body></body>
</html>
server.js
var http = require('http'), io = require('socket.io'),
server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello world</h1>');
});
server.listen(8090);
var socket = io.listen(server);
socket.on('connection', function(client){
console.log('client connected');
client.on('message', function(){
console.log('message arrive');
client.send('some message');
});
client.on('disconnect', function(){
console.log('connection closed');
});
});
Any ideas on what I could be doing wrong? No console messages whatsoever are being displayed. Notably, when i use Firebug to look at the index.html page, no scripts are being embedded, which is odd..Not sure what could be causing that.
You're not loading the socket.io library properly in your index.html file. Try this:
<script type="text/javascript" src="http://localhost:8090/socket.io/socket.io.js"></script>
You're not serving up socket.io.js (or the flash file).
I'd recomend using the CDN:
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
or alternatively use express to serve the socket.io.js file.
edit:
err actually looking closer you're also not serving up index.html
again express could work but for the simple example:
var fs = require('fs');
var index = fs.readFileSync('index.html');
//note the readFileSync is done only in the first tic
.
.
.
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
Use this on the client side as the path !
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
yes, and comment the following line:
// server.listen(8090);

Resources