Helle every body i desired to test sockets,when i'm connected a alert should appear, it work on the computer where Node js is in installed but not in the other computer.
The error :
Failed to load resource: net::ERR_CONNECTION_REFUSED
http://xxx.xxx.xxx.xxx:8080/socket.io/socket.io.js Uncaught
ReferenceError: io is not defined
the code :
server:
var http = require('http');
var fs = require('fs');
var io = require('socket.io');
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type' : 'text/html'});
fs.readFile('./index.html',function(err,content){
res.end(content);
});
}).listen(8080);
io = io.listen(server)
io.sockets.on('connection',function(client){
client.emit('connecte');
});
client :
<html>
<meta charset='utf-8'/>
<head>
<title>my first page</title>
<script src="http://localhost:8080/socket.io/socket.io.js" ></script>
</head>
<body>
<h1>It work</h1>
</body>
<script>
var socket;
socket = io.connect('http://localhost:8080');
socket.on('connecte', function(){
alert('You are connected');
});
</script>
</html>
sorry for the language english is not my first language i try to learn.
Thanks
The Socket.IO docs shows how to use Socket.IO with the built-in http server. Comparing that example and your code you can see you're not using io quite right. Try something like this:
var http = require('http');
var fs = require('fs');
var io = require('socket.io');
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('./index.html', function(err, content) {
res.end(content);
});
});
io = io(server);
server.listen(8080);
io.on('connection', function(client) {
client.emit('connected');
});
Also on an unrelated note, you could pipe() the html file to the client instead of buffering the entire file first:
res.writeHead(200, {'Content-Type': 'text/html'});
fs.createReadStream('index.html').pipe(res);
Related
Hey guys that's one of my first time using node.js and socket.io so i will try to be clear as possible. So i am doing a tutorial for a chat.
And i don't know why the connection is not working when i am running my html page :
http://localhost:8000/user/tchat (Symfony project)
I don't have the
console.log('New user'); (i run the server with "node server.js")
But when i am going to :
http://localhost:1337/
i have the
console.log('This is a test');
I have 2 js files and one html page :
Server.js :
var http = require('http');
httpServer = http.createServer(function(req, res) {
console.log('This is a test');
res.end('Hello World');
});
httpServer.listen(1337);
var io = require('socket.io').listen(httpServer);
io.sockets.on('connection', function(socket) {
console.log('New user');
});
Client.js :
(function($){
var socket = io.connect('http://localhost:1337');
})(jquery);
And the scripts of the html page :
<script src="http://localhost:1337/socket.io/socket.io.js"></script>
<script src="../js/js/client.js"></script>
I'm using a Node.js server to show an HTML file. The HTML uses a Javascript file to get some info but I'm not being able to access that file. Here's my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Swarm Profile</title>
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="/js/script.js"></script>
</body>
</html>
And my Node.js server file:
var http = require('http');
var fs = require('fs');
const hostname = '127.0.0.1';
const port = 9000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
fs.createReadStream("./index.html").pipe(res);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
What should I use to be able to access the script.js file?
There are many static file handler modules already in node, take a look at:
Node static modules
Most popular are: Node-Paperboy and Node-Static
Using node static is as simple as:
var static = require('node-static');
var file = new(static.Server)('./public');
require('http').createServer(function (request, response) {
request.addListener('end', function () {
file.serve(request, response);
});
}).listen(8080);
If you look at code below on the client.on method, I res.write the entire output file because I did not know how to get the message to display with the html file. Is there a similar way of doing this rather than res.writing anything? Res.write is also very slow while when I used res.send it was very fast. Is there any other way I can do this? I am fairly new to node js
//Sending UDP message to TFTP server
//dgram modeule to create UDP socket
var express= require('express'), fs= require('fs'),path = require('path'),util = require('util'),dgram= require('dgram'),client= dgram.createSocket('udp4'),bodyParser = require('body-parser'),app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(express.static('public'));
//Reading in the html file for input page
app.get('/', function(req, res){
var html = fs.readFileSync('index2.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
//reading in html file for output page
app.get('/output', function(req, res){
var html = fs.readFileSync('index3.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
//Recieving UDP message
app.post('/output', function(req, res){
//Define the host and port values of UDP
var HOST= '192.168.0.136';
var PORT= 69;
//Reading in the user's command, converting to hex
var message = new Buffer(req.body.number, 'hex');
//Sends packets to TFTP
client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
if (err) throw err;
});
//Recieving message back and printing it out to webpage
client.on('message', function (message) {
res.write('<html>');
res.write('<head>');
res.write('<meta name="viewport" content="width=device-width">');
res.write('<link rel="stylesheet" type="text/css" href="style.css" media="screen" />');
res.write('</head>');
res.write('</body>');
res.write('<img src="logo.png" alt="rolls royce logo">');
res.write('<ul>');
res.write('<li>Input</li>');
res.write('<li><a class="active" href="/output">Output</a></li>');
res.write(' </ul>');
res.write('</br></br>')
res.write('<div>');
res.write(' <h4>Output is:</h4>');
res.write(message.toString());
res.write('</div>');
res.write('</body>');
res.write('</html>');
});
});
//Setting up listening server
app.listen(3000, "192.168.0.136");
console.log('Listening at 192.168.0.136:3000');
You could write an HTML template, save it into a part of the file system which is accessible from the server, then return it to the HTTP client feeded with the right value.
You could write your own template engine (and use regular expressions to make the correct substitutions), or you could you use Jade for instance.
client.on('message', function(message) {
fs.readFile('/etc/templates/message.jade', function(_, template) {
let body = jade.compile(template)({
message: message.toString()
});
return res.end(body);
});
});
Where message.jade might be
doctype html
html
body
h4 Output is: #{message}
Edit: Answered below
New to Node.js here, I really want to know why this script hangs forever when I'm attempting to connect to the created server.
I've had this happen often enough when I'm trying to create a server and I'm not sure why, as it seems to happen with very similar code:
Node script:
var http = require("http");
var file = require("fs");
var server = http.createServer(function(request, response)
{
file.readFile("chat.html", "UTF-8", function(error, content)
{
if(error) { console.error(error.stack); response.end(); }
response.writeHead(200, {"content-type" : "text/html"});
response.end(content);
});
}).listen(1994, function(){console.log("Listening");});
var websocket = require("socket.io").listen(server);
websocket.sockets.on("connection", function(socket)
{
socket.emit("message", {"message" : "Hello World"});
});
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Chat</title>
<meta charset="utf-8">
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = websocket.connect();
socket.on("message", function(message)
{
console.log(message);
});
</script>
</head>
<body>
<div>Socket file.</div>
</body>
</html>
If there is an error then it should end the response and if there isn't it should end the response, or does it have something to do with the web socket?
Try changing how you are invoking socket.io:
var websocket = require('socket.io')(server);
websocket.on('connection', doStuff);
This example follows directly from the docs on GitHub.
The problem was with websocket.connect(). Socket.io uses io as a global object in the front end, not websocket. So it should have been io.connect().
I am trying to develop a chat application using Express js(jade template ) and socket.io.Here is my app.js
var express = require('express');
var path = require('path');
var http = require('http');
var io = require('socket.io')(http);
var app = express();
//start chat with socket io
io.sockets.on('connection',function(socket){
console.log("connection");
socket.on('send message',function(data,callback){
var msg=data.trim();
if(msg==null){
callback("enter a messsage");
}else{
console.log("chat message"+msg);
io.sockets.emit('new message',{msg:msg});
}
});
});
//end socket
Here is my chat.js file on client side
$(document).ready(function(){
var socket=io.connect('http://localhost:3000');
var $message=$('#message');
var $messageForm=$('#send-message');
//opens a connection and send to sever
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message',$message.val(),function(data){
console.log("data"+data);
});
$message.val('');
});
//read the chat messages from users
socket.on('new message',function(data){
console.log('data.msg');
});
});
chat.jade file
<form id="send-message">
<input type="text" id="message">
<input type="submit" value="submit"/>
</form>
<script src="http://localhost/api/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
I will get 404 error on this file http://localhost:3000/socket.io/socket.io.js. Also get a Uncaught ReferenceError: io is not defined in chat.js script.I think this is because of missing socket.io.js file.
You have a couple of issues.
Serving static files in your jade templates you should be using something like this:
link(rel='text/javascript', href='/js/socket.io.js')
These files will normally be contained within a public directory in your express app.
Then in your app.js you should have something like:
app.use(express.static('public'));
Its explained here on the express site - http://expressjs.com/starter/static-files.html
Elsewhere
Uncaught ReferenceError: io is not defined
$(document).ready(function(){
var socket=io.connect('http://localhost:3000');
This is because you havent defined io on your client. You call connect on something called io but havent declared/defined io anywhere.
Also
You havent created a socket server on your app side. You should be doing something along the lines of:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
});
});
Example
Socket.io have an example chat app on github that you should use as reference.
Your chat.js would be the equivalent of their public/main.js
Your chat.jade is equivalent to their public/index.html
and your app.js matches their index.js