I'm following the tutorial on this tutorial. Here's the code:
var net = require('net')
var chatServer = net.createServer()
chatServer.on('connection', function(client) {
client.write('Hi!\n');
client.write('Bye!\n');
console.log("got msg from http"); //added
client.end()
})
chatServer.listen(9000)
I placed a console.log between the bye and the client.end()
When I run it and hit port 9000, the console.log is outputed twice instead of once.
got msg from http
got msg from http
anyone know why?
Thanks
I'm guessing you're using a browser to test your server. What you're seeing is two different incoming HTTP requests. Try the following code and you will likely see that there are two incoming HTTP requests:
var net = require('net')
var chatServer = net.createServer()
chatServer.on('connection', function(client) {
client.write('Hi!\n');
client.write('Bye!\n');
console.log("got msg from http"); //added
client.on('data', function (data) {
console.log('data: \n%s', data)
});
client.end()
})
chatServer.listen(9000)
The two requests should be GET / and GET /favicon.ico, favicon.ico is the icon which is displayed on the browser tab and bookmarks etc.
Related
I cant seem to get the socket to connect to the server, im not getting any errors but the socket does not seem to be making a connection with the server
var request=require("request");
var server;
request({url: 'http://localhost:3000/api/designrooms'}, function (err,response, body) {
var designroomID = JSON.parse(body)[0]._id;
console.log(designroomID);
server = request({url: 'http://localhost:3000/api/designrooms' + designroomID})
});
var io = require("socket.io").listen(server);
io.on('connection',function(socket){
console.log("connected");
});
Try paste this into developer console (press enter) and see debug result.
localStorage.debug = '*';
javascript and node are asynchronous.
In your case, this line
var io = require("socket.io").listen(server);
is executed before this line :
`server = request({url: 'http://localhost:3000/api/designrooms' + designroomID})`
due to your request callback. So, your server isn't initialized.
Try to move your listener inside the request callback.
I need send data from one page to another page using Socket.io in node. Both pages have different script. The pageA have the script fileA.js, and the pageB have the script fileB.js Here's my code:
fileA.js
$('canvas').on('mouseup', function() {
var dataCan = JSON.stringify(canvas);
socket.emit('upcanvas', dataCan);
});
and this the page that receives that data:
fileB.js
var socket = io.connect('http://localhost:3000');
socket.on('get-data', function(data){
console.log(data);
});
And Here's the server file that receive that data and send the events of socket:
server.js
//Sockets
io.sockets.on('connection', function(socket)
{
socket.on('upcanvas', function(data){
socket.emit('get-data', data);
});
});
But that don't work!, I tried separately fileA.js and fileB.js and the socket works perfectly, but when I try to combine the emit/on events between that two pages, don't occurs nothing. What's wrong in that code?
I've found the solution !, simply this:
//Sockets
io.sockets.on('connection', function(socket)
{
socket.on('upcanvas', function(data){
socket.broadcast.emit('get-data', data);
});
});
Hi I am facing issue with a server client message passing from web client to TCP server . Every time I reconnect to the web page my first 6 messages passes with out delay and the seventh message takes lots of time and the first message repeats again. I think there should be some handler for buffer but I have no idea of how to start it. Help me to solve this. My server and client both are in node socket ( using var net = require('net') ).
my client has to send a response for the ajax call which i made from web page:
$.ajax({
type: 'POST',
url: 'http://localhost:3000/client',
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({name:data+'\r'}),// this is the data i get from web page
done : function(data){
console.log('on success', data);
},
fail : function(error){
console.log('on error', error)
}
})
and my node client
var net = require('net');
var _ = require('lodash');
router.post('/client', function(req, res) {
var inputJSON = req.body;
var HOST = '127.0.0.1';
var PORT = 5000;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
_.forEach(inputJSON, function(value,key){
client.write(value);
// console.log(value);
})
});
//This is the line i missed in my earlier program the client should respond
res.send('success')
});
I am learning node. so you can improvise my code with your comments so i can improve better thanks.
I want to use the tcp net module in node.js, my clients will be browser and also not browser ( device ).
when I tried to run in the browser the index.html, my browser keeps loading looks like it looping..I dont know what's wrong in my code.
I tried use telnet it works fine, the problem is on the browser i cannot load properly the index.html
//app.js
var net = require('net');
var io = require('socket.io')(net);
var clients = [];
var server = net.createServer(function (socket) {
console.log("New client connected");
clients.push(socket);
});
server.listen(1337, 'localhost', false, function () {
console.log('server bound');
});
io.on('connection',function(socket){
socket.emit('news', { hello: 'world' });
});
here is my client code.
http://pastie.org/10115599
Both the browser and socket.io require an http server, not just a TCP server. You can see the code examples in the socket.io documentation. The first server and client code example on that doc page shows you the basics you need.
In fact, the first step in socket.io connection is an http request that is then "upgraded" to the webSocket protocol. So, the server must be an http server. And socket.io hooks into an http server in order to receive incoming connections.
Here's a code example from the socket.io doc:
Server Code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
app.listen(80);
io.on('connection', function (socket) {
// incoming socket.io connection established
});
function handler (req, res) {
// process http requests for normal web page serving
}
Client Code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
The following is a unit test to show the behavior that I'm experiencing, which I recognize as different than what I've experienced before. In essence, the way I was using sockets before (maybe two months ago) stopped working sometime between then and now. I'm not sure what happened. My previously working code has broken.
var socketio = require('socket.io');
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type' : 'text/html' });
var html = "<html><head><script src=\"/socket.io/socket.io.js\"></script>\
<script>var sock = io.connect();\
sock.on('sup', function(data) {\
console.log(\"whoo\");\
sock.emit('howdy', {'hi' : 'ho'});\
});</script></head></html>";
res.end(html);
}).listen(8080);
socketio.listen(server, {log:false}).on('connection', function(socket) {
socket.on('howdy', function(data){console.log("HI!");});
socket.emit("sup", {"hey" :"yo"});
});
What I would expect from the code is the following sequence of events:
socket connects, server emits "sup" message.
client receives "sup" message and logs "whoo"
client sends "howdy" message
server receives "howdy" message and logs "HI!"
Step 4 is not occurring at all. (and therefore I assume step 3 might not be happening, either)
What's going on?
Your client side code is essentially this
var sock = io.connect();
console.log("Gets here");
sock.on('sup', function(data) {
console.log("whoo");
});
sock.emit('howdy', {'hi' : 'ho'});
I'm assuming it will work if you just move the emit into the handler.
var sock = io.connect();
console.log("Gets here");
sock.on('sup', function(data) {
console.log("whoo");
sock.emit('howdy', {'hi' : 'ho'});
});
Or you can try listening for the connect event
var sock = io.connect();
console.log("Gets here");
sock.on('sup', function(data) {
console.log("whoo");
});
sock.on('connect', function() {
sock.emit('howdy', {'hi' : 'ho'});
});
I just updated socket.io, and it's working now.