I've Written This script for the server
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/' , function(req,res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection' , function(socket){
socket.on('send message' , function(data){
io.sockets.emit('new message' , data);
});
});
And This Is The Chatting Page
<html>
<head>
<title>Chat Program</title>
<style>
#chat{
height:400px;
}
</style>
<script src="http://code.jquery.com/jquery-latest-min.js"></script>
<script src="/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
var $messageform = $('#send-message');
var $messagebox = $('#message');
var $chat = $('#chat');
$messageform.submit(function(e){
e.preventDefault();
socket.emit('send message' , $messagebox.val());
$messagebox.val("");
});
socket.on('new message' , function(data){
$chat.append(data + "<br/>");
});
});
</script>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
</body>
</html>
When I Run The script from the console it runs well but when i write something in the chatting box nothing happen... I Don't Know Why But i think that the folder which i downloaded from "npm install socket.io-client" have a problem.
This Line ==> <script src="/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>I Think The Problem is here as the whole code is proper and right (I think)
hint : I'm Node.js beginner
You dont have express configured to serve the file. You have 2 options. You can:
configure express to serve that file explicitly
add this to your app file:
app.get('/socket.io.js' , function(req,res){
res.sendfile(__dirname + '/node_modules/socket.io/node_modules/socket.io-client/socket.io.js');
});
and switch your html script to:
<script src="/socket.io.js"></script>
configure express to server any file in a directory (see this)
Related
I am trying to create socket connection using node js express and socket.io in my project folder which is on Linux(Ubuntu) server. After installing nodejs, npm, socketio and express I am unable to create socket connection. Tried to run node app.js but no output comes. Installation is done following the tutorial http://www.programwitherik.com/getting-started-with-socket-io-node-js-and-express/. I am including code for app.js and index.html
//app.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
});
app.use(express.static(__dirname + '/node_modules'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(8000);
//index.html
<!doctype html>
<html lang="en">
<head>
<script src="http://example.abcd.net/socket-app/jquery/dist/jquery.js"></script>
<script src="http://example.abcd.net:8000/socket.io/socket.io.js"></script>
</head>
<body>
<h1>Hello World!</h1>
<div id="future"></div>
<form id="form" id="chat_form">
<input id="chat_input" type="text">
<input type="submit" value="Send">
</form>
</body>
</html>
<script>
var socket = io.connect();
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
</script>
example.abcd.net is the sample address in which socket-app is the folder which contains app.js and index.html file. Also how to run it on browser as every tutorial runs it using localhost. Similar code works fine when installed on local machine.
Try using io.connect("http://example.abcd.net:8000"); instead of io.connect();
js code. which is a server file
while i am running this below code it is not sending messages when i click the button.
var express = require('express');
var socket = require('socket.io');
var app = express();
var server = app.listen(8000,function(){
console.log("The server is listening on the port 8000");
});
app.use(express.static('public'));
var io = socket(server);
io.on('connection', function(socket){
socket.on("chat", function(data){
io.sockets.emit("chat", data);
});
});
here is my index.html code which also contains
and css file which i am not included here
<!DOCTYPE html>
<html>
<head>
<title>my first chat app</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js">
</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="mario-chat">
<div id="chat-window">
<div id="output"></div>
<div id="feedback"></div>
</div>
<input id="handle" type="text" placeholder="Handle"/>
<input id="message" type="message" placeholder="Message"/>
<button id="send">Send</button>
</div>
<script src="/chat.js"></script>
</body>
</html>
the above code include a stylesheet.css file for looking good.
here is my chat.js file which is client side functionalities.
var socket = io.connect("http://localhost:8000");
var message = document.getElementById("message");
var handle = document.getElementById("handle");
var btn = document.getElementById("send");
var output = document.getElementById("output");
var feedback = document.getElementById("feedback");
btn.addEventListener("click",function(){
socket.emit("chat", {message:message.value,handle:handle.value});
});
socket.on("chat", function(data){
output.innerHTML += '<p><strong>' + data.handle + ':</strong>' +
data.message + '</p>';
});
please rectify me where i am doing mistakes
thanks in advance.
In your client code socket must be created with ws protocol. So,
io.connect("http://localhost:8000"); should be io.connect("ws://localhost:8000");
I'm walking through the Socket.io tutorial on creating a chat room, and I'm having trouble getting my app to log the chat message to the console.
The app is logging when a user connects & disconnects, but it is not logging when a message is passed through.
Any thoughts?
The relevant parts of my index.html page:
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
<body>
<ul id="messages"><ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
My index.js file:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg) {
console.log("message: " + msg);
});
});
I've gotten it to work!
Steps to solution:
- separate the script tag with the event listener into a separate JS file
- include that JS file in the same place the script tag was originally
- load the chatListener when the document is ready
My files now look like this and everything works beautifully:
index.html:
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="main.js"></script>
<body>
<ul id="messages"><ul>
<form action="">
<input class="chat" id="m" autocomplete="off" />
<input class="btn" type="submit" value="Send" />
</form>
</body>
index.js: nothing changed
main.js:
var socket = io();
var chatListener = function() {
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
}
$(document).ready(function() {
chatListener();
})
In the end, I think it was a beginner's JS mistake; I was loading the script at the top of the page (as the tutorial suggested), and the event listener on the form was never registering.
I am a new starter to Node.Js and Redis. I got the Redis cookbook and was trying out the Chat client & Server recipe.
I was wondering if anybody got the code to work or if there is some bug in the code.
I dont see where the sent messages from the client get invoked on the server.
Any help would be great.
Regards,
Tom
Client Code:
<?php
?>
<html>
<head>
<title></title>
<script src="http://192.168.0.118:8000/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
var socket = io.connect('192.168.0.118',{port:8000});
socket.on('message', function(data){
alert(data);
//var li = new Element('li').insert(data);
//$('messages').insert({top: li});
});
</script>
</head>
<body>
<ul id="messages">
<!-- chat messages go here -->
</ul>
<form id="chatform" action="">
<input id="chattext" type="text" value="" />
<input type="submit" value="Send" />
</form>
<script>
$('#chatform').submit(function() {
socket.emit('message', 'test'); //$('chattext').val());
$('chattext').val(""); // cleanup the field
return false;
});
</script>
</body>
</html>
Server Code:
var http = require('http');
io = require('socket.io');
redis = require('redis');
rc = redis.createClient();
//rc1 = redis.createClient();
rc.on("connect",function(){
rc.subscribe("chat");
console.log("In Chat Stream");
});
rc.on("message",function (channel,message){
console.log("Sending hope: " + message);
//rc1.publish("chat","hope");
socketio.sockets.emit('message',message);
});
server = http.createServer(function(req,res){
res.writeHead(200,{'content-type':'text/html'});
res.end('<h1>hello world</h1>');
});
server.listen(8000);
var socketio = io.listen(server);
It looks like you're not listening for any connect / message events from socket.io.. try something like
socketio.sockets.on('connection', function(socket) {
console.log("Got connection");
socket.on('message', function(msg) {
rc1.publish("chat", msg);
});
});
You'll need to uncomment your rc1 up there, you will need that second redis connection
I'm starting playing with node.js and as everybody, I want do a chat.
My idea is run node.js with socket.io in the port 9090, for example, and my client html in the port 8080. My html client will be served independent.
My server:
var sys = require('sys');
var express = require('express');
var io = require('socket.io');
var app = express.createServer();
app.listen(8080);
var socket = io.listen(app);
socket.on('connection', function (client) {
client.on('message', function (msg) {
socket.broadcast(msg);
});
client.on('disconnect', function () {
});
});
My client:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>
$(document).ready(function () {
var socket = new io.Socket("localhost", {port: 8080});
socket.on('connect', function () {
socket.send('A client connected.');
});
socket.on('message', function (message) {
$('div#messages').append($('<p>'), message);
});
socket.on('disconnect', function () {
console.log('disconnected');
});
socket.connect();
$('input').keydown(function (event) {
if(event.keyCode === 13) {
socket.send($('input').val());
$('input').val('');
}
});
});
</script>
</head>
<body>
<input type="text" style="width: 300px;" />
<div id="messages" style="border:solid 1px #000;"> </div>
</body>
</html>
I'm running in ubuntu 11.04 with node.js v0.4.10.
The server works fine, but the client can't do connection, in the console.log on google Chrome I received this message:
XMLHttpRequest cannot load http://localhost:8080/socket.io/xhr-polling//1311465961485. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
The server.js is in a folder in /var/www/cliente/chat/public.
What's the problem?
Your client code is not actually being served from port 8080 as you want.
var sys = require('sys');
var express = require('express');
var io = require('socket.io');
var app = express.createServer();
app.listen(8080);
app.use(express.static(__dirname));
app.get('/', function(req, res){
res.render('index.html', { title: 'Chat' });
});
var socket = io.listen(app);
socket.on('connection', function (client) {
client.on('message', function (msg) {
socket.broadcast(msg);
});
client.on('disconnect', function () {
});
});
This should fix your Access-Control-Allow-Origin errors. Execute node server.js and connect to http://localhost:8080. A couple additional notes:
Make sure you have installed socket.io 0.6.x since that's what you are including in your html file. 0.7.x is backwards incompatible.
With this configuration you'll be running socket.io on the same port you are serving your page from (as opposed to 9090).
When I updated my client to:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://localhost", {port: 8080});
socket.on('connect', function () {
socket.send('A client connected.');
});
socket.on('message', function (msg) {
$('div#messages').append($('<p>'), msg);
});
socket.on('disconnect', function () {
console.log('disconnected');
});
$(document).ready(function(){
$('#btn_send').click(function (event) {
socket.send($('#txt_msg').val());
$('#txt_msg').val('');
});
});
</script>
</head>
<body>
<input type="text" id="txt_msg" style="width: 300px;" /><input type="button" id="btn_send" value="send" />
<div id="messages" style="border:solid 1px #000;"> </div>
</body>
</html>
Everything worked.
I was using a version 0.7 of the socket.io that was the problem: https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7
You cannot make AJAX requests to URLs that are not on the same hostname and port as the current page. It's a security restriction in all web browsers.