I have an instant messaging chat application in the making, and am having problems getting my client to receive data from my server. Could anyone explain to me why this is happening?
app.js
var http = require("http");
var express = require("express");
var socket = require("socket.io");
var app = express();
app.use(express.static(__dirname + "/public"));
var server = http.createServer(app);
server.listen(8080);
var io = socket.listen(server);
io.sockets.on("connection", function(client) {
client.on("join", function(name) {
client.set("nickname", name);
console.log(name + " connected."); // logs name correctly
client.broadcast.emit("names", name);
});
});
index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var server = io.connect("http://localhost:8080");
server.on("connect", function(data) {
nickname = "";
while (nickname == null || nickname.trim() == "") {
nickname = prompt("Enter name");
}
server.emit("join", nickname);
});
server.on("names", function(data) {
document.getElementById("txtNames").value = data;
});
</script>
</head>
<body>
<textarea id="txtNames"></textarea>
</body>
</html>
Do you know what a broadcast is? When you broadcast a message as a result of an event from a socket, The message is emitted to all connected clients except for the socket who triggered the event. Same is your case. If you want to emit names event to your connected client then use
socket.emit("names", name); in your app.js
Related
I am trying to send some json object from the server side to the client side.
var express = require('express');
var app = express();
var server = app.listen(1337);
var io = require('socket.io').listen(server);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function(json) {
io.send('message', json);
});
app.listen(3000);
and on index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data) {
console.log(data);
});
</script>
</body>
</html>
I keep getting this error
Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?
EIO=2&transport=polling&t=1602487581123-0' from origin 'null' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
Use "socket.io": "^2.3.0", for server side, change server side code to following:
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function() {
io.send('message', json);
});
http.listen(3000, () => console.log('HTTP server is listening on port 3000'));
For the CORS header, any origins being allowed by default.
And I recommend you use the latest version of socket.io for the client-side. You can use this CDN.
client side:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js" integrity="sha512-AcZyhRP/tbAEsXCCGlziPun5iFvcSUpEz2jKkx0blkYKbxU81F+iq8FURwPn1sYFeksJ+sDDrI5XujsqSobWdQ==" crossorigin="anonymous"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data, json) {
console.log(data, json);
});
</script>
</body>
</html>
Create HTTP Server for client-side:
☁ 64313396 [master] ⚡ http-server -p 3001
Starting up http-server, serving ./public
Available on:
http://127.0.0.1:3001
http://172.31.160.227:3001
http://10.23.128.81:3001
The output of browser console:
I am beginner to socket.io and trying to make simple hello world like program. It looks like my index.html page loads and connects to the server successfully but the server is not firing the "connection" event. I am sharing my code so that you can figure out what am I doing wrong here.
app.js
var app = require('http');
var io = require('socket.io'), fs = require('fs');
app.createServer(function(req,res){
console.log(req.url);
switch(req.url){
case '/':
fs.readFile('./index.html',function(err,data){
if(err){
res.end('Error');
throw err;
}
res.writeHead(200,{"Context-type":"text/html"});
res.write(data);
res.end();
});
break;
case '/socket.io.js':
fs.readFile('./socket.io.js',function(err,data){
if(err){
res.end('Error');
throw err;
}
res.writeHead(200,{"Context-type":"text/javascript"});
res.write(data);
res.end();
});
}
}).listen(8888);
ios = io.listen(app);
console.log("Listening..");
ios.sockets.on('connection',function(socket){
console.log('connection established.'); //this doesn't show up in CLI
});
Index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Example</title>
<script src="socket.io.js" type="text/javascript"></script>
<script>
var socket = io.connect('http://localhost:8888');
</script>
</head>
<body>
</body>
</html>
Finally I figured it out myself. All I had to do was to
server = require('http').createServer()
and then pass that server to the listener of socket io i.e.
io.listen(server);
What I was doing wrong that I was passing app = require('http'); to the io.listen(app)
I am trying to make a Node.js app that will have an embedded chat. I am using socket.io to create that chat. I have attempted to set up my server / client, but the client does not seem to be connecting. I have my application to set log when sockets connect and disconnect but it never seems to log anything. I figured that the client was being retarded so I opened the Chrome devtools, and typed in:
var socket = io();
oddly, I start seeing a string of failed requests that look like:
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1434334401655-37 404 (Not Found)
So now I'm sure it s my server. here is my server code:
var express = require("express");
var mongoose = require("mongoose");
var io = require("socket.io").listen(app);
// var restAPI = require("./api");
// Set up the application.
var app = express();
app.use(express.static("static"));
// Mount up the rest API
// app.use("/rest", restAPI);
// Default index route.
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
// This will maintian a transcript of the chat
var transcript = []
// This route will return the transcript data as json
app.get("/transcript", function(req, res) {
res.json(JSON.stringify(transcript));
});
// Simple socket.io for chat application
// Lets keep a reference to how many connections we have
var count = 0;
io.sockets.on("connection", function(socket) {
// Increment the number of clients
count++
// Keep a reference to the socket
var current = socket;
// Log the connection
console.log("Connected to: " + current + " at " + Date.now() + ".");
// Log the current number of users
console.log("There are now " + count + "users connected.");
// Handle disconnection
socket.on("disconnect", function() {
// Same routine as connect
console.log(current + ": disconnected at " + Date.now() + ".");
console.log("There are now " + count + "users connected.");
});
});
app.listen(3000);
Here is my HTML client:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport">
<title>Paint</title>
<!-- <script src="/js/application.js"></script> -->
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
</head>
<body>
<header></header>
<nav></nav>
<aside>
<div id="toolbox"></div>
<!-- display: none; by default -->
<div id="chat"></div>
<div class="buttons">
<div class="toolBoxButton">Toolbox</div>
<div class="chatButton">Chat</div>
</div>
</aside>
<section></section>
<footer></footer>
<script>
var socket = io();
</script>
</body>
</html>
Why can't the client connect?
I don't know if this is the only issue, but you're calling this:
var io = require("socket.io").listen(app);
before you assign the app variable so it is undefined.
The request for this URL:
http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1434334401655-37
is how a socket.io connection starts so that is normal. The problem is that the socket.io listener wasn't running properly on the server so nothing was listening for that route.
Also, I don't know if this:
io.sockets.on("connection", function(socket) {...});
works in socket.io v1+. The socket.io doc says to use this:
io.on('connection', function(socket) {...});
I’m having a problem getting started with Node.js.
I’ve created a basic server that I know works, because if I navigate to http://localhost:5000 in my browser I get the expected message. However, I’m having trouble then connecting to this server on the client side with a basic HTML page.
My Node.js app looks like this:
var http = require('http');
var socket = require('socket.io');
var port = process.env.PORT || 5000;
var players;
var app = http.createServer(function(request, response) {
response.write('Server listening to port: ' + port);
response.end();
}).listen(port);
var io = socket.listen(app);
function init() {
io.configure(function() {
io.set('transports', [ 'xhr-polling' ]);
io.set('polling duration', 10);
});
io.sockets.on('connection', onSocketConnection);
};
function onSocketConnection(client) {
console.log('New connection');
console.log(client);
};
init();
My HTML page looks like this (based on https://github.com/mongolab/tractorpush-server/blob/master/index.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/');
socket.on('all', function(data) {
console.log(data);
});
socket.on('complex', function(data) {
console.log(data);
});
</script>
</body>
</html>
I understand that the sockets.io.js file is automatically generated by socket.io, but I just get the following error when I view my index.html file:
Uncaught ReferenceError: io is not defined
How do I actually connect to my server?
I have created a small server for communication using node.js and socket io
Server:
var express = require('/usr/local/lib/node_modules/express')
var io = require('/usr/local/lib/node_modules/socket.io');
var server = express.createServer();
server.listen(8888,'localhost');
io = io.listen(server);
io.of("namespace").on('connection', function(client){
client.emit("message",'connection successful');
client.on('message', function(m){
console.log("received message"+m);
client.broadcast(m);
});
});
Client:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Comet Test</title>
<script src="http://localhost:8888/socket.io/socket.io.js" type="text/javascript"></script>
</head>
<body>
<p><a id='customAlert' href="#" onclick='sendMessage("customAlert")'>publish customAlert</a></p>
<p><a id='customAlert2' href="#" onclick='sendMessage("customAlert2")'>publish customAl
<script type="text/javascript">
// Start the socket
var socket = io.connect('http://localhost:8888/namespace');
socket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
socket.on('message', function(msg){
console.log(msg);
});
function sendMessage(m) {
console.log("sending message"+m);
socket.emit("message",m);
}
</script>
</body>
Communication does not happen, am I doing something wrong here?
If your server is listening on port 8888, you need the client to connect to the server on port 8888.
The following line in your client code:
var socket = io.connect('http://localhost/namespace');
Should read:
var socket = io.connect('http://localhost:8888/namespace');