I started using socket.io for the web game.
Using nodejs express server I tried to write simple test.
In this test server writes timestamp to the client and client returns this timestamp.
After this, server logs time used for sending there and back.
Result was: ping 500 ms +- 10 ms.
And the same results were when I tried to do it with another computer in the local network.
So, I think, delay is so hi because of TCP Nagle algorithm or something similar.
Does anybody knows how to tell nodejs server to flush data as it appears without waiting?
Server code:
var express = require('express'), socketio = require('socket.io');
var app = express.createServer();
var io = socketio.listen(app);
app.use(express.static(__dirname + ''));
app.listen(80);
io.set('transports', ['websocket', 'flashsocket']);
io.sockets.on('connection', function (socket) {
socket.json.send({'message' : 'start'});
socket.on('message', function (msg) {
var time = (new Date()).getTime();
console.log("PING WAS: "+(time - msg.timestamp)+" ms");
socket.json.send({'timestamp' : (new Date()).getTime()});
});
});
Client code:
window.onload = function() {
socket = io.connect('http://localhost:80');
socket.on('message', function (msg) {
socket.json.send({'timestamp' : msg.timestamp});
});
};
Related
Hi i have a node js server and im using sockets to communicate.
Index:
<script src="socket.io/socket.io.js"></script>
Client JS:
var socket = io.connect("http://localhost:8081");
socket.on('hi', function(data){
console.log("g");
console.log(data);
});
So it seems to connect just fine to the server. I have a socket called 'hi' waiting for any incoming messages. I added 2 console logs incase data was null, it would still print something to the console.
Server:
var express = require("express");
var app = express();
var server = require("http").Server(app);
var io = require("socket.io")(server);
var mazeGenerator = require("generate-maze");
app.use(express.static("public"));
io.on("connection", function(socket) { // EDITED
console.log("A player has connected - sending maze data...");
socket.emit("hi", "hi");
});
So when i refresh the page, the client connects and in my CMD i see the "A player has connected..." console log. From then on, its blank from the server or client, I can keep refreshing and it will keep saying a player has connected by the clients console stays blank
Since the connection is proven to be established, I suspect this is an issue of a way you emit the data. Your second parameter hi may not be taken as a data to be transmitted, according to
https://socket.io/docs/server-api/#socket-emit-eventname-args-ack
In my understanding, socket.io emit Object instead of String so can you try this?
io.on("connection", function(socket) {
console.log("A player has connected - sending maze data...");
socket.emit("hi", {data: "hi"});
});
Good evening SO-community, I tried really hard to fix this issue but I think I'll need your wisdom because I really don't know what's the matter here. I have a node.js server which is serving an index.html via express. I am currently starting to use socket.io.
This is the code on my client side:
$( document ).ready(function() {
document.getElementById("start").addEventListener("click", startGame);
function startGame() {
var socket = io(); console.log("Sending request to server");
socket.emit('connectToTable', {tableID: 1});
socket.on('successfulConnection', function(msg){
alert(msg);
}); }
});
This is the code on my server side:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require('express');
var port = process.env.PORT || 3000;
path = require('path');
app.use(express.static(path.join(__dirname, '/')));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("There is someone knocking on the door")
socket.on('connectToTable', function(socket){
console.log("Received player request")
var player = new Player(socket.id);
socket.emit('successfulConnection', "The connection to the server has been successful");
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
On my console on the server I see that "There is someone knocking on the door" gets printed hundreds or thousands of times per second which leads to a CPU load of 100%. At the same time I can see on the client-side (in Chrome) that hundreds of xhr polls are being made.
I really can't figure out why the connection is not established after the first connection attempt and retried sooo often. Furthermore I don't even really understand why it is even using xhr polling instead of websockets.
Help would be very highly appreciated. Thank you so much in advance.
You have to use the same version of socket.io, on the client and on the server (I have had the same problem 5 days ago), check on console with:
npm list socket.io
the version of the server and look if you use the same version on the client, on index.html like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
You can get the url from here:
Versions of socket.io
Regards
I have a NodeWebkit client which connects to a nodejs server using the socket.io library (JavaScript).
The client launches the connect procedure on the application start but the server does not acknoledge any connections... Though the client's socket has the connected attribute to "true".
You should know that I am using socketio-jwt to authentificate the connection.
Github: https://github.com/auth0/socketio-jwt
I know that the connection does work in a way because if I add :
io.sockets.on('connection', function(){console.log("hello");})
It prints hello !
So it seems that event though the connection is somehow made it doesn't want to do the auth part with the library, resulting in... Well... Nothing.
But that's not all !!
Because if I reboot the app (not the server) then the auth works most of the time ! It acts like a race condition... But I dont see how it could possibly be one... Every line of code is geting executed appart of the success callback of authentification.
I tried connecting to a remote server and on my localhost.
I also tried with an other library of socket auth but I've got the same probleme.
This is the server code:
var session = require('express-session');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketioJwt = require('socketio-jwt');
io.sockets.on('connection', socketioJwt.authorize({
secret: 'some secret',
timeout: 15000 // 15 seconds to send the authentication message
})).on('authenticated', function (socket) {
console.log('[Info]: A user connected to socket = ', socket.decoded_token);
});
});
http.listen(5000, function () {
console.log('listening on *:5000');
});
And now the client code:
this.socket = io.connect('http://' + that.hostName +':' + that.port);
var token = jwt.sign({email: "someEail", pwd: "somePwd"}, fromServerSecret);
this.socket.on('connect', function () {
that.socket.emit('authenticate', {token: token}) //send the jwt
.on('authenticated', function () {
console.log("[Info]: Socket login successfull");
})
.on('unauthorized', function (msg) {
console.log("[Warning]: Socket unauthorized: " + JSON.stringify(msg.data));
throw new Error(msg.data.type);
});
});
The server side log "A user connected to socket" is never shown.
If you have an idear ! Thanks for your time.
Why is there a 'that' on socket.emit (client)? I think you should handle it within the same instance of socket.io - using same 'this' as above
I'm trying to test out Node.js and I'm using this code:
// Load the net, and sys modules to create a tcp server.
var net = require('net');
var sys = require('sys');
// Setup a tcp server
var server = net.createServer(function (socket) {
// Every time someone connects, tell them hello and then close the connection.
socket.addListener("connect", function () {
//sys.puts("Connection from " + socket.remoteAddress);
console.log("Person connected.");
var myPacket = [1,2,3,4,5];
sys.puts(myPacket);
socket.end("Hello World\n");
});
});
// Fire up the server bound to port 7000 on localhost
server.listen(7000, "localhost");
// Put a friendly message on the terminal
console.log("TCP server listening on port 7000 at localhost.");
To send a byte array to any connections that show up on port 7000 of local host. Nothing is connecting though, I've tried firefox (localhost:7000, and 127.0.0.1:7000) I tried PuTTy, and even writing my own Java TCP Client to connect to local host, but nothing is working, so I'm convinced that the code is wrong.
Can someone please tell me why my code won't allow connections?
You seem to be overcomplicating the connection part. The callback with the socket is already the connection event so you don't need to listen to it separately. Also, if you want to send binary, use the Buffer class. Here's your code changed. Remember to set your mode to telnet in putty when connecting. I've also changed the end() to write() so it doesn't auto close the connection.
// Load the net, and sys modules to create a tcp server.
var net = require('net');
var sys = require('sys');
// Setup a tcp server
var server = net.createServer(function (socket) {
//sys.puts("Connection from " + socket.remoteAddress);
console.log("Person connected.");
var myPacket = new Buffer([65,66,67,68]);
socket.write(myPacket);
socket.write("Hello World\n");
});
// Fire up the server bound to port 7000 on localhost
server.listen(7000, "localhost");
// Put a friendly message on the terminal
console.log("TCP server listening on port 7000 at localhost.");
I'm relatively new to node.js and it's addons, so this is probably a beginnersquestion.
I'm trying to get a simple HTML page on a webserver connect to a different server running node.js with websocket.io.
My code looks like this:
Client
<script src="socket.io/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
var socket = new io.Socket();
socket.connect('http://127.0.0.1:8080');
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
};
</script>
Serverside
// Require HTTP module (to start server) and Socket.IO
var http = require('http');
var io = require('socket.io');
var port = 8080;
// Start the server at port 8080
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(port);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
console.log('Connection to client established');
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
console.log('Server running at http://127.0.0.1:' + port + '/');
Starting up the server works fine and running http://localhost:8080 in my browser also works, returning 'Hello Socket Lover' as expected. But I want to make a different page talk to the sockets, not run one from node.js.
But when I run it, nothing happens and the Chrome console returns:
Failed to load resource http://undefined/socket.io/1/?t=1333119551736
Failed to load resource http://undefined/socket.io/1/?t=1333119551735
I've been at this all day. Any help?
Have you tried loading the socket.io script not from a relative URL?
You're using:
<script src="socket.io/socket.io.js"></script>
And:
socket.connect('http://127.0.0.1:8080');
You should try:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
And:
socket.connect('http://localhost:8080');
Switch localhost:8080 with whatever fits your current setup.
Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).
You need to make sure that you add forward slash before your link to socket.io:
<script src="/socket.io/socket.io.js"></script>
Then in the view/controller just do:
var socket = io.connect()
That should solve your problem.
Instead of:
var socket = new io.Socket();
Try:
const socket = io();
Also add a server file:
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
app.use(express.static(__dirname + '/public'));
const io = require('socket.io')(server);
const PORT = 5000;
server.listen(PORT, () => {
console.log(`Server is Listening On Port ${PORT}`);
});